import { mkdtemp, rm, mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { ErrorCode } from "@pocketcoder/shared/constants";
import { openDatabase, closeDatabase } from "../../db/database.js";
import { createProject } from "../../db/repositories/projects.js";
import { handleGitFileBase } from "../git-file-base.js";
const execFileAsync = promisify(execFile);
// Suppress logger output in tests
vi.mock("../../utils/logger.js", () => ({
    logger: {
        debug: vi.fn(),
        info: vi.fn(),
        warn: vi.fn(),
        error: vi.fn(),
    },
}));
async function git(cwd, ...args) {
    const { stdout } = await execFileAsync("git", args, { cwd });
    return stdout.trim();
}
describe("git_file_base handler", () => {
    let tempDir;
    let projectDir;
    let dbPath;
    let projectId;
    beforeEach(async () => {
        tempDir = await mkdtemp(join(tmpdir(), "pocketcoder-git-file-base-test-"));
        projectDir = join(tempDir, "project");
        dbPath = join(tempDir, "daemon.db");
        await mkdir(projectDir);
        await git(projectDir, "init");
        await git(projectDir, "config", "user.email", "test@test.com");
        await git(projectDir, "config", "user.name", "Test User");
        await writeFile(join(projectDir, "README.md"), "# Test Project\n");
        await mkdir(join(projectDir, "src"), { recursive: true });
        await writeFile(join(projectDir, "src/app.ts"), "export const app = true;\n");
        await git(projectDir, "add", ".");
        await git(projectDir, "commit", "-m", "initial commit");
        closeDatabase();
        openDatabase(dbPath);
        const project = createProject("test-project", projectDir);
        projectId = project.project_id;
    });
    afterEach(async () => {
        closeDatabase();
        await rm(tempDir, { recursive: true, force: true });
    });
    function createRequest(payload) {
        return {
            type: "git_file_base",
            requestId: "req-1",
            sessionId: projectId,
            payload,
        };
    }
    function createSendCollector() {
        const responses = [];
        const send = (msg) => {
            responses.push(msg);
        };
        return { responses, send };
    }
    it("should return file content at HEAD", async () => {
        const { responses, send } = createSendCollector();
        await handleGitFileBase(createRequest({ path: "README.md" }), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.type).toBe("git_file_base_response");
        expect(resp.error).toBeUndefined();
        expect(resp.payload).toBeDefined();
        expect(resp.payload.path).toBe("README.md");
        expect(resp.payload.ref).toBe("HEAD");
        expect(resp.payload.content).toBe("# Test Project\n");
    });
    it("should return null for new file", async () => {
        // Create a new file that hasn't been committed
        await writeFile(join(projectDir, "new-file.ts"), "export const x = 1;\n");
        await git(projectDir, "add", "new-file.ts");
        const { responses, send } = createSendCollector();
        await handleGitFileBase(createRequest({ path: "new-file.ts" }), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.error).toBeUndefined();
        expect(resp.payload).toBeDefined();
        expect(resp.payload.content).toBeNull();
    });
    it("should return content at specific ref", async () => {
        // Get the initial commit sha
        const sha = await git(projectDir, "rev-parse", "HEAD");
        // Modify and commit
        await writeFile(join(projectDir, "README.md"), "# Updated\n");
        await git(projectDir, "add", ".");
        await git(projectDir, "commit", "-m", "update readme");
        // Request the original content at the first commit
        const { responses, send } = createSendCollector();
        await handleGitFileBase(createRequest({ path: "README.md", ref: sha }), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.error).toBeUndefined();
        expect(resp.payload).toBeDefined();
        expect(resp.payload.ref).toBe(sha);
        expect(resp.payload.content).toBe("# Test Project\n");
    });
    it("should error for non-existent project", async () => {
        const msg = {
            type: "git_file_base",
            requestId: "req-2",
            sessionId: "non-existent-project",
            payload: { path: "README.md" },
        };
        const { responses, send } = createSendCollector();
        await handleGitFileBase(msg, send);
        expect(responses).toHaveLength(1);
        expect(responses[0].error).toBeDefined();
        expect(responses[0].error.code).toBe(ErrorCode.INVALID_REQUEST);
    });
    it("should error for non-git directory", async () => {
        const nonGitDir = join(tempDir, "non-git");
        await mkdir(nonGitDir);
        const project = createProject("non-git-project", nonGitDir);
        const msg = {
            type: "git_file_base",
            requestId: "req-3",
            sessionId: project.project_id,
            payload: { path: "README.md" },
        };
        const { responses, send } = createSendCollector();
        await handleGitFileBase(msg, send);
        expect(responses).toHaveLength(1);
        expect(responses[0].error).toBeDefined();
        expect(responses[0].error.code).toBe(ErrorCode.GIT_NOT_INITIALIZED);
    });
    it("should return file content from subdirectory", async () => {
        const { responses, send } = createSendCollector();
        await handleGitFileBase(createRequest({ path: "src/app.ts" }), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.error).toBeUndefined();
        expect(resp.payload).toBeDefined();
        expect(resp.payload.path).toBe("src/app.ts");
        expect(resp.payload.content).toBe("export const app = true;\n");
    });
});
//# sourceMappingURL=git-file-base.test.js.map