import { FastifyRequest, FastifyReply } from 'fastify';
import { EntityManager } from '@mikro-orm/core';
import { User } from '../entities/user/_User';
import '@fastify/jwt';

declare module '@fastify/jwt' {
    interface FastifyJWT {
        user: User;
    }
}

export const authMiddleware = async (request: FastifyRequest, reply: FastifyReply) => {
    try {
        const em = request.server.orm.em as EntityManager;
        const userId = request.user?.id;

        if (!userId) {
            return reply.status(401).send({ error: 'Unauthorized' });
        }

        const user = await em.findOne(User, { id: userId });
        if (!user) {
            return reply.status(401).send({ error: 'User not found' });
        }

        request.user = user;
    } catch (error) {
        return reply.status(500).send({ error: 'Internal server error' });
    }
}; 