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

// 인스타는 FB 로그인으로 통합 - instagram_basic, instagram_manage_comments 권한으로 들어옴
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/instagram/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 })

    // long lived
    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&access_token=${longToken}`)
    const igUser = await meRes.json()

    // IG 비즈니스 계정 가져오기
    const accRes = await fetch(`https://graph.facebook.com/v20.0/me/accounts?fields=instagram_business_account{id,username},name&access_token=${longToken}`)
    const accData = await accRes.json()
    
    if(accData.data){
      for(const p of accData.data){
        const ig = p.instagram_business_account
        if(ig){
          await pool.query(
            `INSERT INTO connected_accounts (user_id, provider, provider_user_id, name, access_token, parent_id)
             VALUES (?, 'instagram', ?, ?, ?, ?)
             ON DUPLICATE KEY UPDATE name=?, access_token=?`,
            [user.id, ig.id, ig.username, longToken, p.id, ig.username, longToken]
          )
        }
      }
    }

    await pool.query(`UPDATE users SET level = IF(level=1,2,level) WHERE id=?`, [user.id])

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