import { describe, expect, test, vi } from "vitest";

import { createD1Repository } from "../d1-repository";

describe("createD1Repository", () => {
  test("creates an article job using D1 prepare and bind", async () => {
    const run = vi.fn().mockResolvedValue({ success: true });
    const bind = vi.fn().mockReturnValue({ run });
    const prepare = vi.fn().mockReturnValue({ bind });
    const db = { prepare } as unknown as D1Database;

    const repository = createD1Repository(db);

    const job = await repository.createArticleJob({
      source_title: "Title",
      source_body: "Body",
      image_inputs: [],
      publish_platform: "official_site",
      user_instructions: "",
    });

    expect(job.id).toMatch(/^job_/);
    expect(prepare).toHaveBeenCalledWith(expect.stringContaining("insert into article_jobs"));
    expect(bind).toHaveBeenCalledWith(
      job.id,
      null,
      "Title",
      "Body",
      "[]",
      "official_site",
      "",
      "draft",
      "{}",
      job.created_at,
      job.updated_at,
    );
  });

  test("parses article job JSON fields returned from D1", async () => {
    const first = vi.fn().mockResolvedValue({
      id: "job_123",
      brand_template_id: null,
      source_title: "Title",
      source_body: "Body",
      image_inputs: "[]",
      publish_platform: "official_site",
      user_instructions: "",
      status: "draft",
      export_paths: "{}",
      created_at: "2026-06-16T00:00:00.000Z",
      updated_at: "2026-06-16T00:00:00.000Z",
    });
    const bind = vi.fn().mockReturnValue({ first });
    const prepare = vi.fn().mockReturnValue({ bind });
    const db = { prepare } as unknown as D1Database;

    const repository = createD1Repository(db);

    await expect(repository.getArticleJob("job_123")).resolves.toMatchObject({
      id: "job_123",
      image_inputs: [],
      export_paths: {},
    });
  });
});
