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

export async function GET(req: NextRequest){
  const code = req.nextUrl.searchParams.get('code')
  if(!code) return NextResponse.json({ msg: 'code가 없습니다. / 에서 Gmail로 시작하기 버튼으로 접속해주세요.' })

  try {
    const client_id = process.env.GOOGLE_CLIENT_ID!
    const client_secret = process.env.GOOGLE_CLIENT_SECRET!
    const redirect_uri = 'https://i.yjm.kr/api/auth/google/callback'

    const tokenRes = await fetch('https://oauth2.googleapis.com/token', {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: new URLSearchParams({ code, client_id, client_secret, redirect_uri, grant_type: 'authorization_code' })
    })
    const tokenData = await tokenRes.json()
    if(!tokenData.access_token){
      console.error('google token error', tokenData)
      return NextResponse.json(tokenData, { status: 400 })
    }

    const userRes = await fetch('https://www.googleapis.com/oauth2/v2/userinfo', {
      headers: { Authorization: `Bearer ${tokenData.access_token}` }
    })
    const gUser = await userRes.json()

    const isSuper = isSuperAdmin(gUser.email)
    const level = isSuper ? 10 : 1

    // users 테이블에 upsert
    await pool.query(
      `INSERT INTO users (id, email, name, picture, level, last_login)
       VALUES (?, ?, ?, ?, ?, NOW())
       ON DUPLICATE KEY UPDATE name=?, picture=?, last_login=NOW(), level = IF(VALUES(level)=10,10,level)`,
      [gUser.id, gUser.email, gUser.name, gUser.picture, level, gUser.name, gUser.picture]
    )

    // 탈퇴자(0)면 차단
    const [rows]: any = await pool.query('SELECT level FROM users WHERE id=?', [gUser.id])
    if(rows[0]?.level === 0){
      return NextResponse.redirect('https://i.yjm.kr/?error=banned')
    }

    const jwtToken = signUser({ id: gUser.id, email: gUser.email, name: gUser.name, level: rows[0]?.level || level })

    const res = NextResponse.redirect('https://i.yjm.kr/dashboard')
    res.cookies.set('iyjm_token', jwtToken, { httpOnly: true, secure: true, sameSite: 'lax', maxAge: 60*60*24*30, path: '/' })
    return res

  } catch(e:any){
    console.error(e)
    return NextResponse.json({ error: e.message }, { status: 500 })
  }
}
