import { NextRequest, NextResponse } from 'next/server';
import { auditAction } from '@/features/foundation/audit-log/service';
import { cloneApprovalWorkflow, getApprovalWorkflow } 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.crmApprovalWorkflowClone
    });
    const before = await getApprovalWorkflow(id, organization.id);
    const cloned = await cloneApprovalWorkflow(id, organization.id, session.user.id);

    await auditAction({
      organizationId: organization.id,
      userId: session.user.id,
      entityType: 'crm_approval_workflow',
      entityId: cloned.id,
      action: 'clone_approval_workflow',
      beforeData: before,
      afterData: cloned
    });

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