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

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 { reply_text } = await req.json()
  
  const [pages]: any = await pool.query(`SELECT provider_user_id FROM connected_accounts WHERE user_id=? AND provider='facebook_page' LIMIT 1`, [user.id])
  const pageId = pages[0]?.provider_user_id || 'default'

  await pool.query(
    `INSERT INTO auto_reply_rules (user_id, page_id, reply_text, is_active) VALUES (?,?,?,1)
     ON DUPLICATE KEY UPDATE reply_text=?, is_active=1`,
    [user.id, pageId, reply_text, reply_text]
  )
  return NextResponse.json({ ok: true })
}

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({ error: 'login' }, { status: 401 })
  const [rows]: any = await pool.query(`SELECT * FROM auto_reply_rules WHERE user_id=?`, [user.id])
  return NextResponse.json(rows)
}
