import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';
import { z } from 'zod';
import { validateBody } from '@/lib/api-validation';

export const dynamic = 'force-dynamic';

const createOpportunitySchema = z.object({
  name: z.string().min(1, 'Opportunity name is required').max(200),
  customerId: z.string().min(1, 'Customer ID is required'),
  value: z.union([z.string(), z.number()]).optional(),
  probability: z.union([z.string(), z.number()]).optional(),
  expectedCloseDate: z.string().optional(),
  stage: z.string().max(50).optional(),
  notes: z.string().max(2000).optional(),
});

// GET /api/erp/crm/opportunities - List opportunities
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const stage = searchParams.get('status') || searchParams.get('stage');
    const customerId = searchParams.get('customerId');
    const limit = parseInt(searchParams.get('limit') || '50');

    const opportunities = await prisma.opportunity.findMany({
      where: {
        ...(stage ? { stage } : {}),
        ...(customerId ? { customerId } : {})
      },
      include: {
        customer: { select: { id: true, name: true, customerNumber: true } }
      },
      orderBy: [{ stage: 'asc' }, { expectedClose: 'asc' }],
      take: limit
    });

    // Map to expected format for UI
    const mappedOpportunities = opportunities.map(o => ({
      ...o,
      value: o.expectedValue,
      status: o.stage,
      expectedCloseDate: o.expectedClose
    }));

    return NextResponse.json({ opportunities: mappedOpportunities });
  } catch (error) {
    console.error('Opportunities list error:', error);
    return NextResponse.json({ error: 'Failed to fetch opportunities' }, { status: 500 });
  }
}

// POST /api/erp/crm/opportunities - Create opportunity
export async function POST(request: NextRequest) {
  try {
    const validation = await validateBody(request, createOpportunitySchema);
    if (validation.error) return validation.error;
    const { name, customerId, value, probability, expectedCloseDate, stage, notes } = validation.data;

    const opportunity = await prisma.opportunity.create({
      data: {
        name,
        customerId,
        expectedValue: value ? parseFloat(String(value)) : 0,
        probability: probability ? parseInt(String(probability)) : 10,
        expectedClose: expectedCloseDate ? new Date(expectedCloseDate) : null,
        stage: stage || 'prospecting',
        description: notes
      },
      include: {
        customer: { select: { id: true, name: true } }
      }
    });

    return NextResponse.json({ opportunity: { ...opportunity, value: opportunity.expectedValue, status: opportunity.stage } }, { status: 201 });
  } catch (error) {
    console.error('Create opportunity error:', error);
    return NextResponse.json({ error: 'Failed to create opportunity' }, { status: 500 });
  }
}
