import { FastifyRequest, FastifyReply } from 'fastify'
import jwt from 'jsonwebtoken'
import { User } from '../types/context'
import { JWTPayload } from '../types/jwt'

const JWT_SECRET = process.env.JWT_SECRET
if (!JWT_SECRET) {
  throw new Error('JWT_SECRET environment variable is required')
}

export async function authMiddleware(
  request: FastifyRequest,
  _reply: FastifyReply
) {
  // Skip auth for health check and GraphQL introspection
  if (request.url === '/health' || request.method === 'OPTIONS') {
    return
  }

  // Get token from Authorization header
  const authHeader = request.headers.authorization
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    // Allow unauthenticated requests - GraphQL will handle auth per query/mutation
    return
  }

  const token = authHeader.substring(7)

  try {
    const decoded = jwt.verify(token, JWT_SECRET) as JWTPayload
    // Attach user to request
    ;(request as FastifyRequest & { user: User }).user = {
      id: decoded.id,
      email: decoded.email,
      name: decoded.name,
      role: decoded.role,
    }
  } catch (error) {
    // Invalid token - let GraphQL resolvers handle it
    return
  }
}

