import { beforeEach, describe, expect, it, vi } from "vitest";
import type { TrpcContext } from "./_core/context";

const upsertUser = vi.fn();
const getUserByOpenId = vi.fn();

vi.mock("./db", async (importOriginal) => ({
  ...(await importOriginal<typeof import("./db")>()),
  upsertUser,
  getUserByOpenId,
}));

const { appRouter } = await import("./routers");

describe("local administrator credentials", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    getUserByOpenId.mockResolvedValue({ id: 1, openId: "local-admin", role: "admin", isActive: true });
  });

  it("accepts the configured administrator account through the local login endpoint", async () => {
    const username = process.env.LOCAL_ADMIN_USERNAME;
    const password = process.env.LOCAL_ADMIN_PASSWORD;
    expect(username).toBeTruthy();
    expect(password).toBeTruthy();

    const writtenCookies: Array<{ name: string; value: string; options: Record<string, unknown> }> = [];
    const ctx: TrpcContext = {
      user: null,
      req: { protocol: "https", headers: {} } as TrpcContext["req"],
      res: {
        cookie: (name: string, value: string, options: Record<string, unknown>) => writtenCookies.push({ name, value, options }),
      } as TrpcContext["res"],
    };

    const result = await appRouter.createCaller(ctx).localAuth.login({ username: username!, password: password! });

    expect(result).toEqual({ success: true });
    expect(upsertUser).toHaveBeenCalledWith(expect.objectContaining({ openId: "local-admin", role: "admin", isActive: true }));
    expect(writtenCookies).toHaveLength(1);
    expect(writtenCookies[0]?.value).toBeTruthy();
  });
});
