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

export async function GET(req: NextRequest) {
  try {
    const { searchParams } = new URL(req.url)
    const category = searchParams.get('category')
    const search = searchParams.get('search')
    const code = searchParams.get('code')
    const isLaunch = searchParams.get('launch')
    const isPromo = searchParams.get('promo')
    const isLowerPrice = searchParams.get('lowerPrice')
    const isBestseller = searchParams.get('bestseller')
    const fragrance = searchParams.get('fragrance')
    const activeIngredient = searchParams.get('active')
    const minPrice = searchParams.get('minPrice')
    const maxPrice = searchParams.get('maxPrice')
    const sort = searchParams.get('sort') || 'default'
    const limit = parseInt(searchParams.get('limit') || '200')
    const page = parseInt(searchParams.get('page') || '1')
    // Filter by catalog page (the PDF page where the product appears)
    const catalogPage = searchParams.get('catalogPage')

    const where: any = {}

    if (catalogPage) {
      const cp = parseInt(catalogPage, 10)
      if (!Number.isNaN(cp)) where.page = cp
    }

    if (category && category !== 'all') {
      const cat = await db.category.findUnique({ where: { slug: category } })
      if (cat) where.categoryId = cat.id
    }

    if (search) {
      where.OR = [
        { name: { contains: search } },
        { code: { contains: search } },
        { description: { contains: search } },
        { benefits: { contains: search } },
        { fragrance: { contains: search } },
        { activeIngredient: { contains: search } },
      ]
    }

    if (code) {
      where.code = { contains: code }
    }

    // Filter by multiple exact codes (comma-separated) — used for manual pins
    const codes = searchParams.get('codes')
    if (codes) {
      const codeArr = codes.split(',').map(c => c.trim()).filter(Boolean)
      if (codeArr.length > 0) where.code = { in: codeArr }
    }

    if (isLaunch === 'true') where.isLaunch = true
    if (isBestseller === 'true') where.isBestseller = true
    if (isLowerPrice === 'true') where.isLowerPriceYear = true
    if (isPromo === 'true') where.promotionalPrice = { not: null }

    if (fragrance) {
      where.fragrance = { contains: fragrance }
    }
    if (activeIngredient) {
      where.activeIngredient = { contains: activeIngredient }
    }

    if (minPrice || maxPrice) {
      if (maxPrice) {
        where.OR = [
          { promotionalPrice: { lte: parseFloat(maxPrice) } },
          { price: { lte: parseFloat(maxPrice) }, promotionalPrice: null },
        ]
      }
      if (minPrice) {
        where.AND = [
          {
            OR: [
              { promotionalPrice: { gte: parseFloat(minPrice) } },
              { price: { gte: parseFloat(minPrice) }, promotionalPrice: null },
            ]
          }
        ]
      }
    }

    let orderBy: any = { page: 'asc' }
    if (sort === 'price-asc') orderBy = { price: 'asc' }
    if (sort === 'price-desc') orderBy = { price: 'desc' }
    if (sort === 'name') orderBy = { name: 'asc' }
    if (sort === 'discount') orderBy = { discountPercent: 'desc' }

    const [products, total] = await Promise.all([
      db.product.findMany({
        where,
        include: { category: true },
        orderBy,
        skip: (page - 1) * limit,
        take: limit,
      }),
      db.product.count({ where }),
    ])

    return NextResponse.json({
      status: 'success',
      data: products,
      total,
      page,
      pages: Math.ceil(total / limit),
    })
  } catch (error) {
    console.error('Error fetching products:', error)
    return NextResponse.json(
      { status: 'error', message: 'Erro ao buscar produtos' },
      { status: 500 }
    )
  }
}

export async function POST(req: NextRequest) {
  try {
    const body = await req.json()
    const {
      name, code, description, benefits, ingredients, volume, fragrance,
      activeIngredient, price, promotionalPrice, discountPercent, page,
      isLaunch, isBestseller, isLowerPriceYear, isKit, isCombo,
      categoryId, image,
    } = body

    const slug = name.toLowerCase()
      .normalize('NFD').replace(/[\u0300-\u036f]/g, '')
      .replace(/[^a-z0-9\s-]/g, '').trim()
      .replace(/\s+/g, '-').replace(/-+/g, '-')

    const product = await db.product.create({
      data: {
        name, code, slug, description, benefits, ingredients, volume,
        fragrance, activeIngredient, price: parseFloat(price),
        promotionalPrice: promotionalPrice ? parseFloat(promotionalPrice) : null,
        discountPercent: discountPercent ? parseInt(discountPercent) : null,
        page: parseInt(page) || 1,
        isLaunch: !!isLaunch, isBestseller: !!isBestseller,
        isLowerPriceYear: !!isLowerPriceYear, isKit: !!isKit, isCombo: !!isCombo,
        categoryId, image,
      },
      include: { category: true },
    })

    return NextResponse.json({ status: 'success', data: product })
  } catch (error) {
    console.error('Error creating product:', error)
    return NextResponse.json(
      { status: 'error', message: 'Erro ao criar produto' },
      { status: 500 }
    )
  }
}

export async function PUT(req: NextRequest) {
  try {
    const body = await req.json()
    const { id, ...updateData } = body

    if (updateData.price !== undefined) updateData.price = parseFloat(updateData.price)
    if (updateData.promotionalPrice) updateData.promotionalPrice = parseFloat(updateData.promotionalPrice)
    if (updateData.discountPercent !== undefined) updateData.discountPercent = updateData.discountPercent ? parseInt(updateData.discountPercent) : null
    if (updateData.page) updateData.page = parseInt(updateData.page)

    ;(['isLaunch', 'isBestseller', 'isLowerPriceYear', 'isKit', 'isCombo'] as const).forEach(k => {
      if (k in updateData) updateData[k] = !!updateData[k]
    })

    const product = await db.product.update({
      where: { id },
      data: updateData,
      include: { category: true },
    })

    return NextResponse.json({ status: 'success', data: product })
  } catch (error) {
    console.error('Error updating product:', error)
    return NextResponse.json(
      { status: 'error', message: 'Erro ao atualizar produto' },
      { status: 500 }
    )
  }
}

export async function DELETE(req: NextRequest) {
  try {
    const { searchParams } = new URL(req.url)
    const id = searchParams.get('id')

    if (!id) {
      return NextResponse.json(
        { status: 'error', message: 'ID é obrigatório' },
        { status: 400 }
      )
    }

    await db.product.delete({ where: { id } })

    return NextResponse.json({ status: 'success' })
  } catch (error) {
    console.error('Error deleting product:', error)
    return NextResponse.json(
      { status: 'error', message: 'Erro ao deletar produto' },
      { status: 500 }
    )
  }
}
