import type { HttpContext } from '@adonisjs/core/http'
import type { NextFn } from '@adonisjs/core/types/http'
import jwt from 'jsonwebtoken'
import env from '#start/env'
import User from '#models/user'

/**
 * JWT middleware to authenticate requests using JWT tokens
 */
export default class JwtMiddleware {
    async handle(ctx: HttpContext, next: NextFn) {
        const authHeader = ctx.request.header('Authorization')

        if (!authHeader || !authHeader.startsWith('Bearer ')) {
            return ctx.response.unauthorized({
                message: 'Token não fornecido',
            })
        }

        const token = authHeader.substring(7) // Remove 'Bearer ' prefix

        try {
            // Verify and decode the token
            const decoded = jwt.verify(token, env.get('APP_KEY')) as {
                userId: number
                email: string
                username: string
            }

            // Load user from database
            const user = await User.find(decoded.userId)

            if (!user) {
                return ctx.response.unauthorized({
                    message: 'Utilizador não encontrado',
                })
            }

            // Attach user to context for use in controllers
            ctx.auth = { user } as any

            return next()
        } catch (error) {
            return ctx.response.unauthorized({
                message: 'Token inválido ou expirado',
            })
        }
    }
}
