import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { auditAction } from '@/features/foundation/audit-log/service';
import { updateLeadSchema } from '@/features/crm/leads/schemas/lead.schema';
import {
  buildLeadAccessContext,
  deleteLead,
  getLeadById,
  getLeadReferenceData,
  listLeadFollowups,
  updateLead
} from '@/features/crm/leads/server/service';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

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

export async function GET(_request: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { organization, session, membership } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmLeadRead
    });
    const accessContext = buildLeadAccessContext({
      organizationId: organization.id,
      userId: session.user.id,
      membership
    });
    const [lead, followups, referenceData] = await Promise.all([
      getLeadById(id, organization.id, accessContext),
      listLeadFollowups(id, organization.id, accessContext),
      getLeadReferenceData(organization.id)
    ]);

    await auditAction({
      organizationId: organization.id,
      branchId: lead.branchId,
      userId: session.user.id,
      entityType: 'crm_lead',
      entityId: id,
      action: 'view_lead',
      afterData: {
        code: lead.code
      }
    });

    return NextResponse.json({
      success: true,
      time: new Date().toISOString(),
      message: 'Lead loaded successfully',
      lead,
      followups,
      referenceData
    });
  } 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 lead' }, { status: 500 });
  }
}

export async function PATCH(request: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { organization, session, membership } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmLeadUpdate
    });
    const payload = updateLeadSchema.parse(await request.json());
    const accessContext = buildLeadAccessContext({
      organizationId: organization.id,
      userId: session.user.id,
      membership
    });
    const before = await getLeadById(id, organization.id, accessContext);
    const updated = await updateLead(
      id,
      organization.id,
      session.user.id,
      payload,
      accessContext
    );

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

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

export async function DELETE(_request: NextRequest, { params }: Params) {
  try {
    const { id } = await params;
    const { organization, session, membership } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmLeadDelete
    });
    const accessContext = buildLeadAccessContext({
      organizationId: organization.id,
      userId: session.user.id,
      membership
    });
    const before = await getLeadById(id, organization.id, accessContext);
    const deleted = await deleteLead(id, organization.id, accessContext);

    await auditAction({
      organizationId: organization.id,
      branchId: deleted.branchId,
      userId: session.user.id,
      entityType: 'crm_lead',
      entityId: id,
      action: 'delete_lead',
      beforeData: before,
      afterData: deleted
    });

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