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

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

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