import { describe, it, expect, vi, beforeEach } from "vitest";
import fastify from "fastify";
import type { Pool } from "mysql2/promise";
import type { AppConfig } from "../../config.js";
import { registerAuthRoutes } from "../auth-routes.js";
import type { RouteContext } from "../types.js";

const makeConfig = (): AppConfig => ({
  appEnv: "test",
  host: "127.0.0.1",
  port: 0,
  ads: { enabled: false },
  auth: { jwtSecret: "test" },
  cookies: { sameSite: "lax", secure: false },
  smtp: { secure: false },
  db: {
    host: "localhost",
    port: 3306,
    name: "test",
    user: "test",
    password: "test",
    poolSize: 1,
    ssl: false,
    sslRejectUnauthorized: true,
  },
});

const makeDb = () =>
  ({
    execute: vi.fn(async () => {
      throw new Error("DB non attendu");
    }),
  }) as unknown as Pool;

const makeCtx = (): RouteContext => ({
  db: makeDb(),
  config: makeConfig(),
  mailer: null,
  signAccessToken: () => "access",
  signRefreshToken: () => "refresh",
  setRefreshCookie: () => undefined,
  getRefreshCookie: () => undefined,
  clearRefreshCookie: () => undefined,
  requireAuth: async () => undefined,
  requireAdmin: async () => undefined,
  packageVersion: "test",
  appEnv: "test",
});

describe("auth-routes", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("refuse un login sans payload", async () => {
    const app = fastify();
    registerAuthRoutes(app, makeCtx());

    const response = await app.inject({
      method: "POST",
      url: "/auth/login",
      payload: {},
    });

    expect(response.statusCode).toBe(400);
  });

  it("refuse un register sans email/password", async () => {
    const app = fastify();
    registerAuthRoutes(app, makeCtx());

    const response = await app.inject({
      method: "POST",
      url: "/auth/register",
      payload: { email: "", password: "" },
    });

    expect(response.statusCode).toBe(400);
  });
});
