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

export async function GET(request: NextRequest) {
  try {
    const { organization, session, membership } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmLeadRead
    });
    const { searchParams } = request.nextUrl;
    const page = Number(searchParams.get('page') ?? 1);
    const limit = Number(searchParams.get('limit') ?? 10);
    const accessContext = buildLeadAccessContext({
      organizationId: organization.id,
      userId: session.user.id,
      membership
    });
    const [result, referenceData] = await Promise.all([
      listLeads(
        organization.id,
        {
          page,
          limit,
          search: searchParams.get('search') ?? undefined,
          branchId: searchParams.get('branchId') ?? undefined,
          customerId: searchParams.get('customerId') ?? undefined,
          status: searchParams.get('status') ?? undefined,
          awarenessId: searchParams.get('awarenessId') ?? undefined,
          followupStatus: searchParams.get('followupStatus') ?? undefined,
          outcome: searchParams.get('outcome') ?? undefined,
          ownerMarketingUserId: searchParams.get('ownerMarketingUserId') ?? undefined,
          sort: searchParams.get('sort') ?? undefined
        },
        accessContext
      ),
      getLeadReferenceData(organization.id)
    ]);

    return NextResponse.json({
      success: true,
      time: new Date().toISOString(),
      message: 'Leads loaded successfully',
      totalItems: result.totalItems,
      offset: (page - 1) * limit,
      limit,
      items: result.items,
      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 leads' }, { status: 500 });
  }
}

export async function POST(request: NextRequest) {
  try {
    const { organization, session, membership } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmLeadCreate
    });
    const payload = leadSchema.parse(await request.json());
    const accessContext = buildLeadAccessContext({
      organizationId: organization.id,
      userId: session.user.id,
      membership
    });
    const created = await createLead(
      organization.id,
      session.user.id,
      payload,
      accessContext
    );

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

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