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

export async function POST(req: NextRequest){
  const { email, password, name } = await req.json()
  if(!email || !password || !name) return NextResponse.json({ error:'입력 누락' }, { status:400 })
  if(password.length < 6) return NextResponse.json({ error:'비밀번호 6자 이상' }, { status:400 })

  const [exist]: any = await pool.query('SELECT id FROM users WHERE email=? LIMIT 1', [email])
  if(exist.length > 0) return NextResponse.json({ error:'이미 존재하는 이메일' }, { status:409 })

  const hash = await bcrypt.hash(password, 10)
  const id = randomUUID()
  // LV: 1=신규가입, 10=최고
  const level = 1

  await pool.query('INSERT INTO users (id,email,name,password_hash,level,last_login) VALUES (?,?,?,?,?,NOW())', [id,email,name,hash,level])

  const token = jwt.sign({ id, email, name, level, picture:'' }, process.env.JWT_SECRET!, { expiresIn:'30d' })
  const res = NextResponse.json({ ok:true })
  res.cookies.set('iyjm_token', token, { httpOnly:true, path:'/', maxAge:60*60*24*30, secure:true, sameSite:'lax' })
  return res
}
