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

export async function GET(req: NextRequest){
  const token = req.cookies.get('iyjm_token')?.value
  const user = token ? verifyUser(token) : null
  if(!user) return NextResponse.json([], { status: 401 })

  const [rows]: any = await pool.query('SELECT * FROM items WHERE user_id=? AND is_soft_deleted=0 ORDER BY sort_order ASC, id DESC', [user.id])
  return NextResponse.json(rows)
}

export async function POST(req: NextRequest){
  const token = req.cookies.get('iyjm_token')?.value
  const user = token ? verifyUser(token) : null
  if(!user) return NextResponse.json({ error: 'login' }, { status: 401 })

  const { url, title, image, description } = await req.json()

  // LV1 제한: 3개
  const [cntRows]: any = await pool.query('SELECT COUNT(*) as cnt FROM items WHERE user_id=? AND is_soft_deleted=0', [user.id])
  const [userRow]: any = await pool.query('SELECT level FROM users WHERE id=?', [user.id])
  const level = userRow[0]?.level || 1
  if(level === 1 && cntRows[0].cnt >= 3){
    return NextResponse.json({ error: 'LV1은 3개까지만 등록 가능, Facebook 연결시 무제한' }, { status: 403 })
  }

  const [result]: any = await pool.query(
    'INSERT INTO items (user_id, title, url, image, description) VALUES (?,?,?,?,?)',
    [user.id, title||'', url, image||'', description||'']
  )
  return NextResponse.json({ id: result.insertId })
}
