import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { auditUpdate } from '@/features/foundation/audit-log/service';
import {
  getApprovalWorkflow,
  replaceApprovalWorkflowSteps
} from '@/features/foundation/approval/server/service';
import { BUSINESS_ROLES, PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

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

const stepSchema = z.object({
  stepNumber: z.number().int().min(1),
  roleCode: z.enum(BUSINESS_ROLES),
  roleName: z.string().min(1),
  isRequired: z.boolean().optional()
});

const payloadSchema = z.object({
  steps: z.array(stepSchema)
});

export async function PUT(request: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmApprovalWorkflowUpdate
    });
    const payload = payloadSchema.parse(await request.json());
    const before = await getApprovalWorkflow(id, organization.id);
    const steps = await replaceApprovalWorkflowSteps(id, organization.id, payload.steps);

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

    return NextResponse.json({
      success: true,
      message: 'Approval workflow steps updated 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 to update approval workflow steps' },
      { status: 500 }
    );
  }
}
