import type { FastifyRequest, FastifyReply } from 'fastify';
import { authService } from '../services/auth.service.js';

declare module 'fastify' {
  interface FastifyRequest {
    user?: {
      id: string;
      email: string;
      display_name: string;
    };
  }
}

// Required auth middleware - throws error if no valid token
export async function authMiddleware(request: FastifyRequest, reply: FastifyReply) {
  try {
    const authHeader = request.headers.authorization;
    
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return reply.status(401).send({ 
        success: false, 
        error: 'MISSING_TOKEN', 
        message: 'Authorization token required' 
      });
    }

    const token = authHeader.substring(7); // Remove 'Bearer ' prefix
    const decoded = authService.verifyAccessToken(token);
    
    request.user = {
      id: decoded.sub,
      email: decoded.email,
      display_name: decoded.display_name,
    };
  } catch (error) {
    return reply.status(401).send({ 
      success: false, 
      error: 'INVALID_TOKEN', 
      message: 'Invalid or expired token' 
    });
  }
}

// Optional auth middleware - sets user if token is valid, but doesn't fail if missing
export async function optionalAuthMiddleware(request: FastifyRequest, _reply: FastifyReply) {
  try {
    const authHeader = request.headers.authorization;
    
    if (authHeader && authHeader.startsWith('Bearer ')) {
      const token = authHeader.substring(7);
      const decoded = authService.verifyAccessToken(token);
      
      request.user = {
        id: decoded.sub,
        email: decoded.email,
        display_name: decoded.display_name,
      };
    }
  } catch (error) {
    // Silently ignore invalid tokens in optional auth
    request.user = undefined;
  }
}
