import { FastifyRequest, FastifyReply } from 'fastify';
import { verifyToken, JwtPayload } from '@network-tool/shared-crypto';
import { JWT_SECRET } from '../services/auth.service';

declare module 'fastify' {
  interface FastifyRequest {
    user?: JwtPayload;
  }
}

/**
 * JWT 认证中间件
 */
export async function authMiddleware(
  request: FastifyRequest,
  reply: FastifyReply
): Promise<void> {
  const authHeader = request.headers.authorization;
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    reply.status(401).send({ success: false, error: 'UNAUTHORIZED', message: 'Missing or invalid token' });
    return;
  }

  const token = authHeader.substring(7);
  const payload = verifyToken(token, JWT_SECRET);

  if (!payload) {
    reply.status(401).send({ success: false, error: 'TOKEN_EXPIRED', message: 'Token expired or invalid' });
    return;
  }

  request.user = payload;
}

/**
 * Admin 权限中间件（需在 authMiddleware 之后使用）
 */
export async function adminMiddleware(
  request: FastifyRequest,
  reply: FastifyReply
): Promise<void> {
  if (!request.user || request.user.role !== 'admin') {
    reply.status(403).send({ success: false, error: 'FORBIDDEN', message: 'Admin access required' });
  }
}
