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 "./reactivateSite";

describe("reactivateSite", () => {
  it("reactivates INACTIVE site", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const reactivatedSite = {
      ...inactiveSite,
      status: "ACTIVE",
      updatedAt: new Date(),
    };

    mock.enqueueResults([inactiveSite], [reactivatedSite]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.site.status).toBe("ACTIVE");
      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 ACTIVE", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([activeSite]);

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

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