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

export async function GET(req: NextRequest){
  const code = req.nextUrl.searchParams.get('code')
  if(!code) return NextResponse.json({ msg: 'code 없음' }, { status: 400 })
  const token = req.cookies.get('iyjm_token')?.value
  const user = token ? verifyUser(token) : null
  if(!user) return NextResponse.redirect('https://i.yjm.kr/?error=login_required')

  try {
    const client_id = process.env.FB_APP_ID!
    const client_secret = process.env.FB_APP_SECRET!
    const redirect_uri = 'https://i.yjm.kr/api/auth/facebook/callback'

    const tokenRes = await fetch(`https://graph.facebook.com/v20.0/oauth/access_token?client_id=${client_id}&redirect_uri=${encodeURIComponent(redirect_uri)}&client_secret=${client_secret}&code=${code}`)
    const tokenData = await tokenRes.json()
    if(!tokenData.access_token) return NextResponse.json(tokenData, { status: 400 })

    const longRes = await fetch(`https://graph.facebook.com/v20.0/oauth/access_token?grant_type=fb_exchange_token&client_id=${client_id}&client_secret=${client_secret}&fb_exchange_token=${tokenData.access_token}`)
    const longData = await longRes.json()
    const longToken = longData.access_token || tokenData.access_token

    const meRes = await fetch(`https://graph.facebook.com/v20.0/me?fields=id,name,email,picture&access_token=${longToken}`)
    const fbUser = await meRes.json()

    await pool.query(
      `INSERT INTO connected_accounts (user_id, provider, provider_user_id, name, access_token, expires_at)
       VALUES (?, 'facebook', ?, ?, ?, DATE_ADD(NOW(), INTERVAL 60 DAY))
       ON DUPLICATE KEY UPDATE name=?, access_token=?, expires_at=DATE_ADD(NOW(), INTERVAL 60 DAY)`,
      [user.id, fbUser.id, fbUser.name, longToken, fbUser.name, longToken]
    )

    // 페이지 저장
    try {
      const pagesRes = await fetch(`https://graph.facebook.com/v20.0/me/accounts?access_token=${longToken}`)
      const pagesData = await pagesRes.json()
      if(pagesData.data){
        for(const p of pagesData.data){
          await pool.query(
            `INSERT INTO connected_accounts (user_id, provider, provider_user_id, name, access_token, parent_id)
             VALUES (?, 'facebook_page', ?, ?, ?, ?)
             ON DUPLICATE KEY UPDATE name=?, access_token=?`,
            [user.id, p.id, p.name, p.access_token, fbUser.id, p.name, p.access_token]
          )
        }
      }
    } catch(e){ console.log('pages error', e) }

    // 레벨 1 -> 2 자동 승급 (FB 연동시 일반회원)
    await pool.query(`UPDATE users SET level = IF(level=1,2,level) WHERE id=?`, [user.id])

    return NextResponse.redirect('https://i.yjm.kr/dashboard?fb_connected=1')
  } catch(e:any){
    console.error(e)
    return NextResponse.json({ error: e.message }, { status: 500 })
  }
}
