import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';

/** Map a raw DB lead to the shape the UI expects */
function normalizeLead(l: any) {
  return {
    ...l,
    // Aliased fields expected by all dashboard pages
    name:         l.businessName,
    qualityScore: Math.round((l.confidenceScore ?? 0) * 100),
    savedAt:      l.createdAt,
    industry:     l.category ?? 'Unknown',
    // Normalize status: DB stores lowercase 'new' etc. but prospects page
    // uses uppercase enum values.  Map on read so the UI just works.
    status: normalizeStatus(l.status),
  };
}

function normalizeStatus(raw: string): string {
  const map: Record<string, string> = {
    new:           'PROSPECT',
    prospect:      'PROSPECT',
    qualified:     'INTERESTED',
    shortlisted:   'INTERESTED',
    contacted:     'CONTACTED',
    unqualified:   'REJECTED',
    converted:     'CONVERTED',
    rejected:      'REJECTED',
  };
  return map[raw?.toLowerCase()] ?? raw?.toUpperCase() ?? 'PROSPECT';
}

function denormalizeStatus(ui: string): string {
  const map: Record<string, string> = {
    PROSPECT:   'new',
    CONTACTED:  'contacted',
    INTERESTED: 'qualified',
    CONVERTED:  'converted',
    REJECTED:   'unqualified',
  };
  return map[ui] ?? ui.toLowerCase();
}

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const status  = searchParams.get('status');
  const query   = searchParams.get('q');
  const limit   = parseInt(searchParams.get('limit') || '100', 10);
  const skip    = parseInt(searchParams.get('skip')  || '0',   10);

  try {
    const where: any = {};

    if (status) {
      // Accept both UI enum and raw DB value
      where.status = denormalizeStatus(status);
    }
    if (query) {
      where.OR = [
        { businessName: { contains: query } },
        { email:        { contains: query } },
        { city:         { contains: query } },
        { tags:         { contains: query } },
      ];
    }

    // Filter leads with complete contact info if requested
    if (searchParams.get('complete') === 'true') {
      where.AND = [
        ...(where.AND || []),
        { email:   { not: null } },
        { email:   { not: '' } },
        { website: { not: null } },
        { website: { not: '' } },
        { phone:   { not: null } },
        { phone:   { not: '' } },
      ];
    }

    const [rawLeads, total] = await Promise.all([
      prisma.lead.findMany({ where, orderBy: { createdAt: 'desc' }, take: limit, skip }),
      prisma.lead.count({ where }),
    ]);

    return NextResponse.json({ leads: rawLeads.map(normalizeLead), total });
  } catch (error) {
    console.error('GET /api/leads error:', error);
    return NextResponse.json({ error: 'Failed to fetch leads' }, { status: 500 });
  }
}

export async function PATCH(request: Request) {
  try {
    const body = await request.json();
    const { id, status, ...rest } = body;

    if (!id) return NextResponse.json({ error: 'Lead ID required' }, { status: 400 });

    const data: any = { ...rest };
    if (status) data.status = denormalizeStatus(status);

    const updated = await prisma.lead.update({ where: { id }, data });
    return NextResponse.json(normalizeLead(updated));
  } catch (error) {
    console.error('PATCH /api/leads error:', error);
    return NextResponse.json({ error: 'Failed to update lead' }, { status: 500 });
  }
}

export async function DELETE(request: Request) {
  try {
    const { searchParams } = new URL(request.url);
    const queryId = searchParams.get('id');

    if (queryId) {
      // Single delete via query param: DELETE /api/leads?id=xxx
      await prisma.lead.delete({ where: { id: queryId } });
      return NextResponse.json({ success: true, deleted: 1 });
    }

    // Bulk delete via request body: DELETE /api/leads  { ids: [...] }
    const body = await request.json().catch(() => ({}));
    const ids: string[] = body.ids ?? [];

    if (ids.length === 0) {
      return NextResponse.json({ error: 'Provide ?id= or body { ids: [...] }' }, { status: 400 });
    }

    const { count } = await prisma.lead.deleteMany({ where: { id: { in: ids } } });
    return NextResponse.json({ success: true, deleted: count });
  } catch (error) {
    console.error('DELETE /api/leads error:', error);
    return NextResponse.json({ error: 'Failed to delete lead(s)' }, { status: 500 });
  }
}
