import jwt from 'jsonwebtoken'
import { randomBytes } from 'crypto'

const JWT_SECRET = process.env.JWT_SECRET || 'your-super-secret-jwt-key'
const JWT_EXPIRES_IN = process.env.JWT_EXPIRES_IN || '1h'
const REFRESH_TOKEN_EXPIRES_IN = process.env.REFRESH_TOKEN_EXPIRES_IN || '7d'

export interface JWTPayload {
  userId: string
  email: string
  role: string
  type: 'access' | 'refresh'
}

export function generateAccessToken(userId: string, email: string, role: string): string {
  const payload: JWTPayload = {
    userId,
    email,
    role,
    type: 'access'
  }

  return jwt.sign(payload, JWT_SECRET, {
    expiresIn: JWT_EXPIRES_IN,
    issuer: 'vibecli-auth',
    audience: 'vibecli-users'
  })
}

export function generateRefreshToken(): string {
  return randomBytes(32).toString('hex')
}

export function verifyAccessToken(token: string): JWTPayload {
  try {
    const decoded = jwt.verify(token, JWT_SECRET, {
      issuer: 'vibecli-auth',
      audience: 'vibecli-users'
    }) as JWTPayload

    if (decoded.type !== 'access') {
      throw new Error('Invalid token type')
    }

    return decoded
  } catch (error) {
    throw new Error('Invalid or expired token')
  }
}

export function getTokenExpirationTime(): Date {
  const expiresIn = JWT_EXPIRES_IN
  let milliseconds = 0

  if (expiresIn.endsWith('h')) {
    milliseconds = parseInt(expiresIn) * 60 * 60 * 1000
  } else if (expiresIn.endsWith('m')) {
    milliseconds = parseInt(expiresIn) * 60 * 1000
  } else if (expiresIn.endsWith('d')) {
    milliseconds = parseInt(expiresIn) * 24 * 60 * 60 * 1000
  } else {
    milliseconds = parseInt(expiresIn) * 1000
  }

  return new Date(Date.now() + milliseconds)
}

export function getRefreshTokenExpirationTime(): Date {
  const expiresIn = REFRESH_TOKEN_EXPIRES_IN
  let milliseconds = 0

  if (expiresIn.endsWith('h')) {
    milliseconds = parseInt(expiresIn) * 60 * 60 * 1000
  } else if (expiresIn.endsWith('m')) {
    milliseconds = parseInt(expiresIn) * 60 * 1000
  } else if (expiresIn.endsWith('d')) {
    milliseconds = parseInt(expiresIn) * 24 * 60 * 60 * 1000
  } else {
    milliseconds = parseInt(expiresIn) * 1000
  }

  return new Date(Date.now() + milliseconds)
}