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

// =========================================================================
// /api/pins/hidden — shared hidden auto-pins (admin hides via "×")
//
//   POST   /api/pins/hidden  body { code } → hide a product's auto-pin
//   DELETE /api/pins/hidden?code=C         → un-hide (re-show) a product's pin
//
// Hidden pins are shared so "when I remove a pin, it stays saved" across
// devices, sessions, and visitors. Keyed by product code (a hidden pin is
// hidden on every page that product appears on).
// =========================================================================

export async function POST(req: NextRequest) {
  try {
    const body = await req.json()
    const { code } = body
    if (typeof code !== 'string' || !code.trim()) {
      return NextResponse.json(
        { status: 'error', message: 'code é obrigatório' },
        { status: 400 }
      )
    }
    const created = await db.hiddenPin.upsert({
      where: { code },
      update: {}, // already hidden — nothing to update
      create: { code },
    })
    return NextResponse.json({
      status: 'success',
      data: { code: created.code },
    })
  } catch (error) {
    console.error('Error hiding pin:', error)
    return NextResponse.json(
      { status: 'error', message: 'Erro ao ocultar pin' },
      { status: 500 }
    )
  }
}

export async function DELETE(req: NextRequest) {
  try {
    const { searchParams } = new URL(req.url)
    const code = searchParams.get('code')
    if (!code) {
      return NextResponse.json(
        { status: 'error', message: 'code é obrigatório' },
        { status: 400 }
      )
    }
    await db.hiddenPin.deleteMany({ where: { code } })
    return NextResponse.json({ status: 'success' })
  } catch (error) {
    console.error('Error un-hiding pin:', error)
    return NextResponse.json(
      { status: 'error', message: 'Erro ao reexibir pin' },
      { status: 500 }
    )
  }
}
