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

// =========================================================================
// /api/pins — shared pin positions + manual pins (visible to ALL visitors)
//
//   GET    /api/pins            → { positions: [...], manualPins: [...] }
//   PUT    /api/pins            → upsert one position { page, code, x, y }
//   DELETE /api/pins?page=N&code=C → remove one position
// =========================================================================

export async function GET() {
  try {
    const [positions, manualPins, hiddenPins] = await Promise.all([
      db.pinPosition.findMany(),
      db.manualPin.findMany({ orderBy: { createdAt: 'asc' } }),
      db.hiddenPin.findMany({ orderBy: { createdAt: 'asc' } }),
    ])
    return NextResponse.json({
      status: 'success',
      positions: positions.map(p => ({ page: p.page, code: p.code, x: p.x, y: p.y })),
      manualPins: manualPins.map(m => ({ page: m.page, code: m.code, createdAt: m.createdAt.getTime() })),
      hiddenPins: hiddenPins.map(h => h.code),
    })
  } catch (error) {
    console.error('Error fetching shared pins:', error)
    return NextResponse.json(
      { status: 'error', message: 'Erro ao buscar pins compartilhados' },
      { status: 500 }
    )
  }
}

export async function PUT(req: NextRequest) {
  try {
    const body = await req.json()
    const { page, code, x, y } = body
    if (
      typeof page !== 'number' ||
      typeof code !== 'string' ||
      typeof x !== 'number' ||
      typeof y !== 'number'
    ) {
      return NextResponse.json(
        { status: 'error', message: 'page, code, x, y são obrigatórios' },
        { status: 400 }
      )
    }
    const cx = Math.max(0, Math.min(1, x))
    const cy = Math.max(0, Math.min(1, y))

    const upserted = await db.pinPosition.upsert({
      where: { page_code: { page, code } },
      update: { x: cx, y: cy },
      create: { page, code, x: cx, y: cy },
    })
    return NextResponse.json({ status: 'success', data: upserted })
  } catch (error) {
    console.error('Error upserting pin position:', error)
    return NextResponse.json(
      { status: 'error', message: 'Erro ao salvar posição do pin' },
      { status: 500 }
    )
  }
}

export async function DELETE(req: NextRequest) {
  try {
    const { searchParams } = new URL(req.url)
    const page = parseInt(searchParams.get('page') || '', 10)
    const code = searchParams.get('code')
    if (Number.isNaN(page) || !code) {
      return NextResponse.json(
        { status: 'error', message: 'page e code são obrigatórios' },
        { status: 400 }
      )
    }
    await db.pinPosition.deleteMany({ where: { page, code } })
    return NextResponse.json({ status: 'success' })
  } catch (error) {
    console.error('Error deleting pin position:', error)
    return NextResponse.json(
      { status: 'error', message: 'Erro ao remover posição do pin' },
      { status: 500 }
    )
  }
}
