import type { NextFunction, Request, Response } from 'express'

import {
  requireActiveWorkerSession,
  verifyWorkerSessionToken,
  type WorkerSession,
} from '../../services/worker-platform/index.js'
import { createHttpError, sendRouteError } from '../../utils/http.js'

export async function requireWorkerSession(
  req: Request,
  res: Response,
  next: NextFunction,
): Promise<void> {
  try {
    req.workerSession = await verifyWorkerSessionToken(extractWorkerBearerToken(req))
    next()
  } catch (error) {
    sendRouteError(res, error, '接单端鉴权失败', '[worker/auth]')
  }
}

export function requireActiveWorker(req: Request, res: Response, next: NextFunction): void {
  try {
    requireActiveWorkerSession(req.workerSession)
    next()
  } catch (error) {
    sendRouteError(res, error, '接单账号审核状态无效', '[worker/auth/active]')
  }
}

export function getRequiredWorkerSession(req: Request): WorkerSession {
  if (req.workerSession) {
    return req.workerSession
  }

  throw createHttpError('未登录或登录已失效', {
    statusCode: 401,
    errorCode: 'worker_auth_required',
  })
}

export function extractWorkerBearerToken(req: Request): string {
  const token = extractOptionalWorkerBearerToken(req)
  if (token) {
    return token
  }

  throw createHttpError('未登录或登录已失效', {
    statusCode: 401,
    errorCode: 'worker_auth_required',
  })
}

export function extractOptionalWorkerBearerToken(req: Request): string {
  const authorization = String(req.headers.authorization || '').trim()
  const matched = authorization.match(/^Bearer\s+(.+)$/i)
  return matched?.[1]?.trim() || ''
}
