import { describe, it, expect, beforeAll, afterAll } from "vitest";
import { POST as loginPOST } from "@/app/api/auth/login/route";
import { POST as logoutPOST } from "@/app/api/auth/logout/route";
import { prisma } from "@/lib/db";
import { hashPassword } from "@/lib/auth/password";
import { SETTINGS } from "@/lib/settings";

beforeAll(async () => {
  const hash = await hashPassword("pmtestpass");
  await prisma.setting.upsert({
    where: { key: SETTINGS.PASSWORD_HASH },
    update: { value: hash },
    create: { key: SETTINGS.PASSWORD_HASH, value: hash },
  });
});

afterAll(async () => {
  await prisma.$disconnect();
});

function makeReq(body: unknown): Request {
  return new Request("http://localhost/api/auth/login", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(body),
  });
}

describe("POST /api/auth/login", () => {
  it("returns 200 + Set-Cookie on correct password", async () => {
    const res = await loginPOST(makeReq({ password: "pmtestpass" }));
    expect(res.status).toBe(200);
    const cookie = res.headers.get("set-cookie");
    expect(cookie).toMatch(/pm_session=/);
    expect(cookie).toMatch(/HttpOnly/);
  });

  it("returns 401 on wrong password", async () => {
    const res = await loginPOST(makeReq({ password: "wrong" }));
    expect(res.status).toBe(401);
  });

  it("returns 400 on missing password", async () => {
    const res = await loginPOST(makeReq({}));
    expect(res.status).toBe(400);
  });
});

describe("POST /api/auth/logout", () => {
  it("clears the session cookie", async () => {
    const res = await logoutPOST();
    expect(res.status).toBe(200);
    const cookie = res.headers.get("set-cookie");
    expect(cookie).toMatch(/pm_session=;/);
    expect(cookie).toMatch(/Max-Age=0/);
  });
});
