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

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

const workflowSchema = z.object({
  code: z.string().min(1).optional(),
  name: z.string().min(1).optional(),
  entityType: z.string().min(1).optional(),
  isActive: z.boolean().optional()
});

export async function GET(_request: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { organization } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmApprovalWorkflowRead
    });
    const workflow = await getApprovalWorkflow(id, organization.id);

    return NextResponse.json({
      success: true,
      time: new Date().toISOString(),
      message: 'Approval workflow loaded successfully',
      workflow
    });
  } 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 to load approval workflow' }, { status: 500 });
  }
}

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

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

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

export async function DELETE(_request: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmApprovalWorkflowDelete
    });
    const result = await softDeleteApprovalWorkflow(id, organization.id);

    await auditDelete({
      organizationId: organization.id,
      userId: session.user.id,
      entityType: 'crm_approval_workflow',
      entityId: id,
      beforeData: result.before,
      afterData: result.after
    });

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