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

// =========================================================================
// /api/pins/manual — shared manually-added pins (admin adds via "+")
//
//   POST   /api/pins/manual  body { code, page } → add manual pin
//   DELETE /api/pins/manual?page=N&code=C        → remove manual pin
// =========================================================================

export async function POST(req: NextRequest) {
  try {
    const body = await req.json()
    const { code, page } = body
    if (typeof code !== 'string' || typeof page !== 'number') {
      return NextResponse.json(
        { status: 'error', message: 'code e page são obrigatórios' },
        { status: 400 }
      )
    }
    const created = await db.manualPin.upsert({
      where: { page_code: { page, code } },
      update: {}, // no fields to update — createdAt stays
      create: { page, code },
    })
    return NextResponse.json({
      status: 'success',
      data: {
        page: created.page,
        code: created.code,
        createdAt: created.createdAt.getTime(),
      },
    })
  } catch (error) {
    console.error('Error adding manual pin:', error)
    return NextResponse.json(
      { status: 'error', message: 'Erro ao adicionar pin manual' },
      { 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.manualPin.deleteMany({ where: { page, code } })
    return NextResponse.json({ status: 'success' })
  } catch (error) {
    console.error('Error removing manual pin:', error)
    return NextResponse.json(
      { status: 'error', message: 'Erro ao remover pin manual' },
      { status: 500 }
    )
  }
}
