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

export const dynamic = 'force-dynamic';

export async function GET(request: NextRequest) {
  try {
    const products = await prisma.swagProduct.findMany({
      include: {
        variants: {
          orderBy: [{ size: 'asc' }, { color: 'asc' }],
        },
      },
      orderBy: { name: 'asc' },
    });

    // Calculate inventory stats
    const stats = {
      totalProducts: products.length,
      totalVariants: products.reduce((sum: number, p: any) => sum + p.variants.length, 0),
      totalStock: products.reduce((sum: number, p: any) => 
        sum + p.variants.reduce((vs: number, v: any) => vs + v.stock, 0), 0),
      lowStock: products.reduce((sum: number, p: any) => 
        sum + p.variants.filter((v: any) => v.stock > 0 && v.stock <= 10).length, 0),
      outOfStock: products.reduce((sum: number, p: any) => 
        sum + p.variants.filter((v: any) => v.stock === 0).length, 0),
    };

    return NextResponse.json({ products, stats });
  } catch (error) {
    console.error('Error fetching inventory:', error);
    return NextResponse.json({ error: 'Failed to fetch inventory' }, { status: 500 });
  }
}

export async function PUT(request: NextRequest) {
  try {
    const { variantId, stock, adjustment } = await request.json();

    const variant = await prisma.swagVariant.findUnique({
      where: { id: variantId },
      include: { product: true },
    });

    if (!variant) {
      return NextResponse.json({ error: 'Variant not found' }, { status: 404 });
    }

    const newStock = adjustment !== undefined 
      ? variant.stock + adjustment 
      : stock;

    const updated = await prisma.swagVariant.update({
      where: { id: variantId },
      data: { stock: Math.max(0, newStock) },
    });

    // Sync with inventory system
    const linkedProduct = await prisma.product.findFirst({
      where: { sku: variant.product.sku },
    });

    if (linkedProduct) {
      await prisma.stockMovement.create({
        data: {
          productId: linkedProduct.id,
          type: adjustment !== undefined ? 'adjustment' : 'count',
          quantity: adjustment || (newStock - variant.stock),
          reason: `Swag inventory ${adjustment !== undefined ? 'adjustment' : 'recount'}`,
          reference: `swag-${variantId}`,
        },
      });
    }

    return NextResponse.json({ variant: updated });
  } catch (error) {
    console.error('Error updating inventory:', error);
    return NextResponse.json({ error: 'Failed to update inventory' }, { status: 500 });
  }
}
