import { NextRequest, NextResponse } from 'next/server';
import { requireApiAuth } from '@/lib/auth';
import { prisma } from '@/lib/prisma';
import { productSchema } from '@/lib/validation';

export async function GET(request: NextRequest) {
  const authError = await requireApiAuth(request);
  if (authError) return authError;

  const query = request.nextUrl.searchParams.get('query')?.trim() || '';

  const products = await prisma.product.findMany({
    where: {
      isActive: true,
      ...(query
        ? {
            OR: [
              { name: { contains: query } },
              { sku: { contains: query } },
              { barcode: { contains: query } }
            ]
          }
        : {})
    },
    orderBy: [{ name: 'asc' }],
    take: 200
  });

  return NextResponse.json(products);
}

export async function POST(request: NextRequest) {
  const authError = await requireApiAuth(request);
  if (authError) return authError;

  let body: unknown;
  try {
    body = await request.json();
  } catch {
    return NextResponse.json({ error: 'JSON inválido' }, { status: 400 });
  }

  const parsed = productSchema.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json({ error: parsed.error.issues[0]?.message || 'Datos inválidos' }, { status: 400 });
  }

  try {
    const product = await prisma.product.create({
      data: {
        ...parsed.data,
        sku: parsed.data.sku || null,
        barcode: parsed.data.barcode || null,
        supplier: parsed.data.supplier || null
      }
    });
    return NextResponse.json(product, { status: 201 });
  } catch (error) {
    const message =
      error instanceof Error && error.message.includes('Unique constraint')
        ? 'SKU o código de barras ya existe'
        : 'No se pudo crear el producto';
    return NextResponse.json({ error: message }, { status: 400 });
  }
}
