import jwt from 'jsonwebtoken'

const JWT_SECRET = process.env.JWT_SECRET || 'dev-secret-change-me'
const SUPER_ADMIN_RAW = process.env.SUPER_ADMIN_EMAIL || process.env.SUPER_ADMIN_EMAILS || 'itcontrol1998@gmail.com'

export function getSuperAdminEmails(): string[] {
  return SUPER_ADMIN_RAW.split(',').map(e=>e.trim().toLowerCase()).filter(Boolean)
}

export function isSuperAdmin(email: string){
  if(!email) return false
  return getSuperAdminEmails().includes(email.toLowerCase())
}

export function signUser(payload: {id: string, email: string, name: string, level: number}){
  return jwt.sign(payload, JWT_SECRET, { expiresIn: '30d' })
}

export function verifyUser(token: string){
  try {
    return jwt.verify(token, JWT_SECRET) as any
  } catch(e){ return null }
}

export function requireLevel(user: any, min: number){
  if(!user) throw new Error('로그인 필요')
  if((user.level||0) < min) throw new Error('권한 없음')
}
