import type { FastifyInstance } from "fastify";
import { z } from "zod";
import { verifyPassword } from "../../crypto/password.js";
import { findByEmail, findById } from "../../auth/users.js";
import { writeAudit } from "../../audit/audit.js";

const loginSchema = z.object({
  email: z.string().email(),
  password: z.string().min(1),
});

export async function authRoutes(app: FastifyInstance): Promise<void> {
  // POST /auth/login -> { token, user }
  app.post("/auth/login", async (req, reply) => {
    const parsed = loginSchema.safeParse(req.body);
    if (!parsed.success) {
      return reply.code(400).send({ error: "E-mail ou senha inválidos." });
    }
    const { email, password } = parsed.data;

    const user = await findByEmail(email);
    // Mensagem genérica + verificação mesmo sem usuário (evita enumeração e
    // timing). Só falha cedo se não houver usuário ativo.
    const ok =
      user && user.active
        ? await verifyPassword(password, user.password_hash)
        : false;
    if (!user || !ok) {
      return reply.code(401).send({ error: "Credenciais inválidas." });
    }

    const token = app.jwt.sign({
      sub: user.id,
      email: user.email,
      role: user.role,
    });
    await writeAudit({ userId: user.id, action: "auth.login", entity: "panel_user", entityId: user.id });

    return reply.send({
      token,
      user: { id: user.id, name: user.name, email: user.email, role: user.role },
    });
  });

  // GET /auth/me -> usuário da sessão atual
  app.get("/auth/me", { preHandler: app.authenticate }, async (req, reply) => {
    const user = await findById(req.user.sub);
    if (!user || !user.active) {
      return reply.code(401).send({ error: "Sessão inválida." });
    }
    return reply.send({
      id: user.id,
      name: user.name,
      email: user.email,
      role: user.role,
    });
  });
}
