import fp from 'fastify-plugin';
import jwt from '@fastify/jwt';
import bcrypt from 'bcrypt';
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';

const SALT_ROUNDS = 10;

export default fp(async function authPlugin(fastify: FastifyInstance) {
  await fastify.register(jwt, {
    secret: process.env.JWT_SECRET!,
  });

  fastify.decorate('authenticate', async function (request: FastifyRequest, reply: FastifyReply) {
    try {
      await request.jwtVerify();
    } catch {
      reply.code(401).send({ error: 'Non authentifié' });
    }
  });

  fastify.decorate('hashPassword', (password: string) => bcrypt.hash(password, SALT_ROUNDS));

  fastify.decorate('comparePassword', (password: string, hash: string) =>
    bcrypt.compare(password, hash)
  );
});
