import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } 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 mock = createKyselyMock<Namespace["main-db"]>();
    const deactivatedSite = {
      ...activeSite,
      status: "INACTIVE",
      updatedAt: new Date(),
    };

    mock.enqueueResults([activeSite], [deactivatedSite]);

    const result = await mock.withTx((trx) => run(trx, { 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(mock.updates.length).toBeGreaterThan(0);
  });

  it("throws when site does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await mock.withTx((trx) => run(trx, { siteId: "nonexistent" }));

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

  it("throws when site is already INACTIVE", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([inactiveSite]);

    const result = await mock.withTx((trx) => run(trx, { siteId: inactiveSite.id }));

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