import type { NextFunction, Request, Response } from 'express'
import { unauthorized } from '../lib/errors.js'
import { readAccessToken, type Identity } from '../lib/tokens.js'

declare module 'express-serve-static-core' {
  interface Request {
    identity?: Identity
  }
}

const bearer = (header: string | undefined) => {
  if (!header?.startsWith('Bearer ')) return null
  return header.slice('Bearer '.length).trim()
}

export const requireAuth = (req: Request, _res: Response, next: NextFunction) => {
  const token = bearer(req.header('authorization'))
  if (!token) {
    next(unauthorized())
    return
  }
  try {
    req.identity = readAccessToken(token)
    next()
  } catch (error) {
    next(error)
  }
}

export const optionalAuth = (req: Request, _res: Response, next: NextFunction) => {
  const token = bearer(req.header('authorization'))
  if (!token) {
    next()
    return
  }
  try {
    req.identity = readAccessToken(token)
    next()
  } catch (error) {
    next(error)
  }
}
