import { NextRequest, NextResponse } from 'next/server';
import { MovementType } from '@prisma/client';
import { getAdminPassword, requireApiAuth } from '@/lib/auth';
import { applyMovement } from '@/lib/stock';
import { movementSchema } from '@/lib/validation';

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 = movementSchema.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json({ error: parsed.error.issues[0]?.message || 'Datos inválidos' }, { status: 400 });
  }

  const { productId, quantity, type, note, allowNegative, adminPassword } = parsed.data;

  if (type === 'SALE' && allowNegative) {
    if (!adminPassword || adminPassword !== getAdminPassword()) {
      return NextResponse.json({ error: 'Password admin inválido para permitir stock negativo' }, { status: 403 });
    }
  }

  try {
    const result = await applyMovement({
      productId,
      type: type as MovementType,
      quantity,
      note,
      allowNegative: type === 'SALE' ? allowNegative : false
    });

    return NextResponse.json(result);
  } catch (error) {
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'No se pudo registrar el movimiento' },
      { status: 400 }
    );
  }
}
