import { afterEach, describe, expect, it } from "bun:test";
import { mkdtempSync, rmSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { reseedDatabase } from "../src/database";
import { createTask, getOrganizationSummary, getTaskDetail, listOrganizations, listTasks, updateTask } from "../src/repository";

let tempDir: string | null = null;

function createDb() {
  tempDir = mkdtempSync(join(tmpdir(), "mock-task-api-"));
  return reseedDatabase(join(tempDir, "test.sqlite"));
}

afterEach(() => {
  if (tempDir) {
    rmSync(tempDir, { recursive: true, force: true });
    tempDir = null;
  }
});

describe("mock task repository", () => {
  it("lists seeded organizations and tasks", () => {
    const db = createDb();

    const organizations = listOrganizations(db);
    const tasks = listTasks(db, { orgId: "org_acme" });

    expect(organizations.length).toBe(3);
    expect(tasks.length).toBeGreaterThan(0);
    expect(organizations[0]).toHaveProperty("openTaskCount");
  });

  it("returns task detail with labels and comments", () => {
    const db = createDb();

    const task = getTaskDetail(db, "task_1001");

    expect(task?.labels.length).toBeGreaterThan(0);
    expect(task?.comments.length).toBeGreaterThan(0);
  });

  it("creates and updates a task", () => {
    const db = createDb();

    const created = createTask(db, {
      orgId: "org_acme",
      projectId: "proj_acme_ops",
      assigneeUserId: "user_acme_2",
      title: "Mock task from test",
      priority: "low",
    });

    expect(created?.title).toBe("Mock task from test");

    const updated = updateTask(db, created!.id as string, {
      status: "done",
      assigneeUserId: null,
    });

    expect(updated?.status).toBe("done");
    expect(updated?.assigneeUserId).toBeNull();
  });

  it("returns org summary status counts", () => {
    const db = createDb();

    const summary = getOrganizationSummary(db, "org_acme");

    expect(summary).not.toBeNull();
    expect(summary?.statusBreakdown.length).toBeGreaterThan(0);
  });
});
