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

export async function GET() {
  try {
    const farms = await prisma.farm.findMany({ orderBy: { createdAt: 'desc' } });
    return NextResponse.json(farms);
  } catch {
    return NextResponse.json({ error: 'Error fetching farms' }, { status: 500 });
  }
}

export async function POST(request: Request) {
  try {
    const body = await request.json();
    const {
      name, ruc, farmCode, exporterName, address, city, country, phone, contactName,
      contactOrders, phoneOrders, emailOrders, notifyOrders,
      contactLabels, phoneLabels, emailLabels, notifyLabels,
      contactCoord, phoneCoord, emailCoord, notifyCoord
    } = body;

    const cleanRuc = ruc?.toString().trim();
    if (cleanRuc) {
      const existing = await prisma.farm.findFirst({
        where: { ruc: cleanRuc }
      });
      if (existing) {
        return NextResponse.json({
          error: `Ya existe una finca registrada con el RUC ${cleanRuc} (${existing.name}). El número de RUC es único.`
        }, { status: 400 });
      }
    }

    const farm = await prisma.farm.create({
      data: {
        name,
        ruc: cleanRuc || null,
        farmCode,
        exporterName,
        address,
        city,
        country,
        phone,
        contactName,
        contactOrders: contactOrders || null,
        phoneOrders: phoneOrders || null,
        emailOrders: emailOrders || null,
        notifyOrders: notifyOrders !== false,
        contactLabels: contactLabels || null,
        phoneLabels: phoneLabels || null,
        emailLabels: emailLabels || null,
        notifyLabels: notifyLabels !== false,
        contactCoord: contactCoord || null,
        phoneCoord: phoneCoord || null,
        emailCoord: emailCoord || null,
        notifyCoord: notifyCoord !== false
      } as any
    });
    return NextResponse.json(farm);
  } catch (error: any) {
    return NextResponse.json({ error: error.message || 'Error creating farm' }, { status: 500 });
  }
}
