import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { auditAction } from '@/features/foundation/audit-log/service';
import { updateApprovalStepSchema } from '@/features/crm/approval/schemas/approval-step.schema';
import {
  deleteApprovalWorkflowStep,
  getApprovalWorkflow,
  updateApprovalWorkflowStep
} 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; stepId: string }>;
};

export async function PATCH(request: NextRequest, { params }: Params) {
  try {
    const { id, stepId } = await params;
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmApprovalWorkflowStepManage
    });
    const payload = updateApprovalStepSchema.parse(await request.json());
    const before = await getApprovalWorkflow(id, organization.id);
    const updated = await updateApprovalWorkflowStep(stepId, organization.id, payload);

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

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

export async function DELETE(_request: NextRequest, { params }: Params) {
  try {
    const { id, stepId } = await params;
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmApprovalWorkflowStepManage
    });
    const before = await getApprovalWorkflow(id, organization.id);
    const result = await deleteApprovalWorkflowStep(stepId, organization.id);

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

    return NextResponse.json({
      success: true,
      message: 'Approval workflow step deleted successfully'
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }
    if (error instanceof Error) {
      return NextResponse.json({ message: error.message }, { status: 400 });
    }
    return NextResponse.json({ message: 'Unable delete approval workflow step' }, { status: 500 });
  }
}
