import type { FastifyInstance } from 'fastify';
import { authService } from '../services/authService.js';
import { authenticate } from '../middleware/auth.js';

export async function authRoutes(fastify: FastifyInstance) {
  // POST /api/v1/auth/login
  fastify.post('/login', async (req, reply) => {
    const { email, password } = req.body as { email: string; password: string };
    if (!email || !password) {
      return reply.status(400).send({ error: 'email and password are required' });
    }
    try {
      const result = await authService.login(email, password);
      return reply.send(result);
    } catch (err: unknown) {
      const e = err as { statusCode?: number; message: string };
      return reply.status(e.statusCode ?? 500).send({ error: e.message });
    }
  });

  // POST /api/v1/auth/logout  (stateless JWT — client discards token)
  fastify.post('/logout', { preHandler: authenticate }, async (_req, reply) => {
    return reply.send({ ok: true });
  });

  // GET /api/v1/auth/me
  fastify.get('/me', { preHandler: authenticate }, async (req, reply) => {
    const user = await authService.getUser(req.user!.sub);
    if (!user) return reply.status(404).send({ error: 'User not found' });
    return reply.send(user);
  });
}
