import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { auditAction } from '@/features/foundation/audit-log/service';
import { reorderApprovalStepsSchema } from '@/features/crm/approval/schemas/approval-step.schema';
import {
  getApprovalWorkflow,
  reorderApprovalWorkflowSteps
} from '@/features/crm/approval/server/workflow-builder.service';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

type Params = {
  params: Promise<{ id: string }>;
};

export async function POST(request: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmApprovalWorkflowStepManage
    });
    const payload = reorderApprovalStepsSchema.parse(await request.json());
    const before = await getApprovalWorkflow(id, organization.id);
    const steps = await reorderApprovalWorkflowSteps(id, organization.id, payload);

    await auditAction({
      organizationId: organization.id,
      userId: session.user.id,
      entityType: 'crm_approval_step',
      entityId: id,
      action: 'reorder_approval_steps',
      beforeData: before.steps,
      afterData: steps
    });

    return NextResponse.json({
      success: true,
      message: 'Approval workflow steps reordered successfully'
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }
    if (error instanceof z.ZodError) {
      return NextResponse.json(
        { message: error.issues[0]?.message ?? 'Invalid payload' },
        { status: 400 }
      );
    }
    if (error instanceof Error) {
      return NextResponse.json({ message: error.message }, { status: 400 });
    }
    return NextResponse.json({ message: 'Unable reorder approval workflow steps' }, { status: 500 });
  }
}
