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

// Compute the real stock for a product by summing all variant stocks.
// For variant products, the per-variant stocks are the source of truth.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function computeEffectiveStock(product: any): number {
  const colors = Array.isArray(product.colors) ? product.colors : null
  const sizes = Array.isArray(product.sizes) ? product.sizes : null

  if (sizes?.length && colors?.length) {
    // Both: stock is in sizes[].colorStocks[]
    return sizes.reduce((total: number, s: any) => {
      if (Array.isArray(s.colorStocks) && s.colorStocks.length > 0) {
        return total + s.colorStocks.reduce((sum: number, cs: any) => sum + (Number(cs.stock) || 0), 0)
      }
      return total + (Number(s.stock) || 0)
    }, 0)
  }
  if (colors?.length) {
    return colors.reduce((sum: number, c: any) => sum + (Number(c.stock) || 0), 0)
  }
  if (sizes?.length) {
    return sizes.reduce((sum: number, s: any) => sum + (Number(s.stock) || 0), 0)
  }
  return product.stock
}

// GET /api/products - Get all products with optional filters
export async function GET(request: Request) {
  try {
    const { searchParams } = new URL(request.url)
    const category = searchParams.get('category')
    const subcategory = searchParams.get('subcategory')
    const q = searchParams.get('q')
    const isNew = searchParams.get('isNew')
    const isUsed = searchParams.get('isUsed')

    const where: Prisma.ProductWhereInput = {}

    if (category) where.category = category
    if (subcategory) where.subcategory = subcategory
    if (isNew === 'true') where.isNew = true
    if (isUsed === 'true') where.isUsed = true

    if (q) {
      where.OR = [
        { name: { contains: q, mode: 'insensitive' } },
        { description: { contains: q, mode: 'insensitive' } },
        { shortDescription: { contains: q, mode: 'insensitive' } },
        { brand: { contains: q, mode: 'insensitive' } },
      ]
    }

    const products = await prisma.product.findMany({
      where,
      include: {
        reviews: {
          where: { status: 'approved' },
        },
      },
      orderBy: { createdAt: 'desc' },
    })

    // Ensure product.stock always reflects the real total (variant stocks included)
    const enrichedProducts = products.map(p => ({
      ...p,
      stock: computeEffectiveStock(p),
    }))

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