import { describe, expect, it } from "vitest";
import { InMemoryStore } from "../../src/store.js";
import { makeClock } from "../helpers.js";

describe("予約/承認/キャンセル (TC-FR-BC-002/006)", () => {
  async function mk(store: InMemoryStore) {
    const list = await store.createList("L");
    return store.createBroadcast({ name: "B", subject: "S", body_html: "x", list_id: list.id });
  }

  it("下書きを予約できる (TC-FR-BC-002)", async () => {
    const store = new InMemoryStore(makeClock().now);
    const bc = await mk(store);
    expect((await store.getBroadcast(bc.id))?.status).toBe("draft");
    expect(await store.scheduleBroadcast(bc.id, 12345)).toBe(true);
    const after = await store.getBroadcast(bc.id);
    expect(after?.status).toBe("scheduled");
    expect(after?.scheduled_at).toBe(12345);
  });

  it("scheduled のときのみキャンセル可 (TC-FR-BC-006)", async () => {
    const store = new InMemoryStore(makeClock().now);
    const bc = await mk(store);
    // draft ではキャンセル不可
    expect(await store.cancelBroadcast(bc.id)).toBe(false);
    await store.scheduleBroadcast(bc.id, 1);
    expect(await store.cancelBroadcast(bc.id)).toBe(true);
    expect((await store.getBroadcast(bc.id))?.status).toBe("canceled");
    // 一度キャンセルしたら再キャンセル不可
    expect(await store.cancelBroadcast(bc.id)).toBe(false);
  });

  it("sending 到達後はキャンセル不可 (TC-FR-BC-006)", async () => {
    const store = new InMemoryStore(makeClock().now);
    const bc = await mk(store);
    await store.scheduleBroadcast(bc.id, 1);
    await store.claimDueBroadcasts(2); // → sending
    expect(await store.cancelBroadcast(bc.id)).toBe(false);
  });
});
