import { NextRequest, NextResponse } from 'next/server'
import { pool } from '@/lib/db'
import bcrypt from 'bcryptjs'
import jwt from 'jsonwebtoken'

export async function POST(req: NextRequest){
  const { email, password } = await req.json()
  if(!email || !password) return NextResponse.json({ error:'입력 누락' }, { status:400 })

  const [rows]: any = await pool.query('SELECT * FROM users WHERE email=? LIMIT 1', [email])
  const user = rows[0]
  if(!user) return NextResponse.json({ error:'존재하지 않는 이메일' }, { status:401 })
  if(!user.password_hash) return NextResponse.json({ error:'소셜 가입 계정입니다. 구글 로그인을 이용하세요' }, { status:401 })

  const ok = await bcrypt.compare(password, user.password_hash)
  if(!ok) return NextResponse.json({ error:'비밀번호 불일치' }, { status:401 })

  if(user.level === 0) return NextResponse.json({ error:'차단된 계정입니다' }, { status:403 })

  const token = jwt.sign({ id:user.id, email:user.email, name:user.name, level:user.level, picture:user.picture }, process.env.JWT_SECRET!, { expiresIn:'30d' })

  const res = NextResponse.json({ ok:true, user:{ id:user.id, email:user.email, name:user.name, level:user.level } })
  res.cookies.set('iyjm_token', token, { httpOnly:true, path:'/', maxAge:60*60*24*30, secure:true, sameSite:'lax' })
  await pool.query('UPDATE users SET last_login=NOW() WHERE id=?', [user.id])
  return res
}
