import jwt from 'jsonwebtoken'
import type { Response } from 'express'

const JWT_SECRET = process.env.JWT_SECRET || 'wing-jwt-secret-change-in-production'
const COOKIE_NAME = 'WING_SESSION'
const TOKEN_EXPIRY = '24h'
const COOKIE_MAX_AGE = 24 * 60 * 60 * 1000

export interface JwtPayload {
  sub: string
  acnt: string
  name: string
  roles: string[]
}

export function signToken(payload: JwtPayload): string {
  return jwt.sign(payload, JWT_SECRET, { expiresIn: TOKEN_EXPIRY })
}

export function verifyToken(token: string): JwtPayload {
  return jwt.verify(token, JWT_SECRET) as JwtPayload
}

export function setTokenCookie(res: Response, token: string): void {
  res.cookie(COOKIE_NAME, token, {
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production',
    sameSite: 'lax',
    maxAge: COOKIE_MAX_AGE,
    path: '/',
  })
}

export function clearTokenCookie(res: Response): void {
  res.clearCookie(COOKIE_NAME, {
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production',
    sameSite: 'lax',
    path: '/',
  })
}

export function getTokenFromCookie(cookies: Record<string, string>): string | null {
  return cookies[COOKIE_NAME] || null
}
