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

// 1. 웹훅 인증 (GET) - FB가 호출
export async function GET(req: NextRequest){
  const mode = req.nextUrl.searchParams.get('hub.mode')
  const token = req.nextUrl.searchParams.get('hub.verify_token')
  const challenge = req.nextUrl.searchParams.get('hub.challenge')
  
  const VERIFY_TOKEN = process.env.FB_VERIFY_TOKEN || 'iyjm_verify_2026'
  if(mode === 'subscribe' && token === VERIFY_TOKEN){
    return new NextResponse(challenge, { status: 200 })
  }
  return new NextResponse('Forbidden', { status: 403 })
}

// 2. 실제 이벤트 수신 (POST) - 자동댓글 핵심
export async function POST(req: NextRequest){
  try {
    const body = await req.json()
    console.log('FB Webhook:', JSON.stringify(body).slice(0,2000))

    // page feed comment
    if(body.object === 'page' || body.object === 'instagram'){
      for(const entry of body.entry || []){
        for(const change of entry.changes || []){
          if(change.field === 'feed' && change.value.item === 'comment'){
            const commentId = change.value.comment_id
            const message = change.value.message
            const pageId = entry.id

            // DB에서 해당 페이지 토큰 찾기
            const [rows]: any = await pool.query(
              `SELECT user_id, access_token FROM connected_accounts WHERE provider_user_id=? AND provider IN ('facebook_page','facebook') LIMIT 1`,
              [pageId]
            )
            if(!rows[0]) continue

            // 자동 댓글 설정 가져오기
            const [ruleRows]: any = await pool.query(
              `SELECT reply_text FROM auto_reply_rules WHERE user_id=? AND page_id=? AND is_active=1 LIMIT 1`,
              [rows[0].user_id, pageId]
            )
            let replyText = ruleRows[0]?.reply_text || '문의 감사합니다! DM으로 상세 정보 보내드릴게요 😊'

            // 키워드 필터가 있으면 키워드 포함시에만
            // (MVP: 무조건 답글)

            // Graph API로 답글 달기
            await fetch(`https://graph.facebook.com/v20.0/${commentId}/comments`, {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({ message: replyText, access_token: rows[0].access_token })
            })

            // 로그 저장
            await pool.query(
              `INSERT INTO auto_reply_logs (user_id, page_id, comment_id, comment_text, reply_text) VALUES (?,?,?,?,?)`,
              [rows[0].user_id, pageId, commentId, message, replyText]
            )
          }

          // Instagram comment
          if(change.field === 'comments'){
            const commentId = change.value.id
            const text = change.value.text
            const mediaId = change.value.media?.id
            const igUserId = entry.id

            const [rows]: any = await pool.query(
              `SELECT user_id, access_token FROM connected_accounts WHERE provider_user_id=? AND provider='instagram' LIMIT 1`,
              [igUserId]
            )
            if(!rows[0]) continue

            const [ruleRows]: any = await pool.query(
              `SELECT reply_text FROM auto_reply_rules WHERE user_id=? AND page_id=? AND is_active=1 LIMIT 1`,
              [rows[0].user_id, igUserId]
            )
            let replyText = ruleRows[0]?.reply_text || '감사합니다! DM 확인해주세요!'

            await fetch(`https://graph.facebook.com/v20.0/${commentId}/replies`, {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({ message: replyText, access_token: rows[0].access_token })
            })
          }
        }
      }
    }

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