import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import { SiteNotFoundError, InvalidStateError } from "../lib/errors.generated";
import { activeSite, inactiveSite } from "../testing/fixtures";
import { run } from "./deactivateSite";

describe("deactivateSite", () => {
  it("deactivates ACTIVE site", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const deactivatedSite = {
      ...activeSite,
      status: "INACTIVE",
      updatedAt: new Date(),
    };

    spies.select.mockReturnValue(activeSite);
    spies.update.mockReturnValue(deactivatedSite);

    const result = await run(db, { siteId: activeSite.id });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.site.status).toBe("INACTIVE");
      expect(result.value.site.updatedAt).not.toBeNull();
    }
    expect(spies.update).toHaveBeenCalled();
  });

  it("throws when site does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValue(undefined);

    const result = await run(db, { siteId: "nonexistent" });

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(SiteNotFoundError);
    }
  });

  it("throws when site is already INACTIVE", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValue(inactiveSite);

    const result = await run(db, { siteId: inactiveSite.id });

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvalidStateError);
    }
  });
});
