module.exports = async function (fastify, opts) {
  // Inscription
  fastify.post('/register', {
    schema: {
      body: {
        type: 'object',
        required: ['email', 'password', 'name'],
        properties: {
          email: { type: 'string', format: 'email' },
          password: { type: 'string', minLength: 6 },
          name: { type: 'string' }
        }
      }
    }
  }, async (request, reply) => {
    const { email, password, name } = request.body;

    try {
      // Vérifier si l'utilisateur existe déjà
      const existingUser = await fastify.prisma.user.findUnique({
        where: { email }
      });

      if (existingUser) {
        return reply.code(400).send({ error: 'Cet email est déjà utilisé' });
      }

      // Créer un client Stripe
      const customer = await fastify.createCustomer(email, name);

      // Hacher le mot de passe
      const hashedPassword = await fastify.hashPassword(password);

      // Créer l'utilisateur
      const user = await fastify.prisma.user.create({
        data: {
          email,
          password: hashedPassword,
          name,
          stripeId: customer.id
        }
      });

      // Générer un token JWT
      const token = fastify.jwt.sign({ id: user.id }, { expiresIn: '7d' });

      return {
        user: {
          id: user.id,
          email: user.email,
          name: user.name,
          subscription: user.subscription
        },
        token
      };
    } catch (error) {
      fastify.log.error(error);
      return reply.code(500).send({ error: 'Erreur lors de l\'inscription' });
    }
  });

  // Connexion
  fastify.post('/login', {
    schema: {
      body: {
        type: 'object',
        required: ['email', 'password'],
        properties: {
          email: { type: 'string', format: 'email' },
          password: { type: 'string' }
        }
      }
    }
  }, async (request, reply) => {
    const { email, password } = request.body;

    try {
      // Trouver l'utilisateur
      const user = await fastify.prisma.user.findUnique({
        where: { email }
      });

      if (!user) {
        return reply.code(401).send({ error: 'Email ou mot de passe incorrect' });
      }

      // Vérifier le mot de passe
      const passwordMatch = await fastify.comparePassword(password, user.password);

      if (!passwordMatch) {
        return reply.code(401).send({ error: 'Email ou mot de passe incorrect' });
      }

      // Générer un token JWT
      const token = fastify.jwt.sign({ id: user.id }, { expiresIn: '7d' });

      return {
        user: {
          id: user.id,
          email: user.email,
          name: user.name,
          subscription: user.subscription
        },
        token
      };
    } catch (error) {
      fastify.log.error(error);
      return reply.code(500).send({ error: 'Erreur lors de la connexion' });
    }
  });
};