import { mkdtemp, rm, mkdir, writeFile, readFile, stat } 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 { handleGitDiscard } from "../git-discard.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_discard handler", () => {
    let tempDir;
    let projectDir;
    let dbPath;
    let projectId;
    beforeEach(async () => {
        tempDir = await mkdtemp(join(tmpdir(), "pocketcoder-git-discard-test-"));
        projectDir = join(tempDir, "project");
        dbPath = join(tempDir, "daemon.db");
        await mkdir(projectDir);
        // Initialize a git repo with initial commit
        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\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(opts) {
        return {
            type: "git_discard",
            requestId: "req-1",
            sessionId: projectId,
            payload: opts,
        };
    }
    function createSendCollector() {
        const responses = [];
        const send = (msg) => {
            responses.push(msg);
        };
        return { responses, send };
    }
    it("should discard changes to specific files", async () => {
        // Modify a tracked file
        await writeFile(join(projectDir, "README.md"), "Modified content\n");
        const { responses, send } = createSendCollector();
        await handleGitDiscard(createRequest({ paths: ["README.md"] }), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.type).toBe("git_discard_response");
        expect(resp.error).toBeUndefined();
        expect(resp.payload).toBeDefined();
        expect(resp.payload.discarded).toBe(1);
        // Verify file is restored
        const content = await readFile(join(projectDir, "README.md"), "utf-8");
        expect(content).toBe("# Test\n");
    });
    it("should discard all tracked changes without all flag", async () => {
        // Modify tracked files
        await writeFile(join(projectDir, "README.md"), "Modified\n");
        const { responses, send } = createSendCollector();
        await handleGitDiscard(createRequest({}), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.error).toBeUndefined();
        expect(resp.payload).toBeDefined();
        // Verify file is restored
        const content = await readFile(join(projectDir, "README.md"), "utf-8");
        expect(content).toBe("# Test\n");
    });
    it("should discard all changes and delete untracked files with all flag", async () => {
        // Modify tracked and create untracked
        await writeFile(join(projectDir, "README.md"), "Modified\n");
        await writeFile(join(projectDir, "untracked.txt"), "untracked\n");
        const { responses, send } = createSendCollector();
        await handleGitDiscard(createRequest({ all: true }), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.error).toBeUndefined();
        expect(resp.payload).toBeDefined();
        expect(resp.payload.discarded).toBeGreaterThanOrEqual(2);
        // Verify tracked file is restored
        const content = await readFile(join(projectDir, "README.md"), "utf-8");
        expect(content).toBe("# Test\n");
        // Verify untracked file is deleted
        await expect(stat(join(projectDir, "untracked.txt"))).rejects.toThrow("ENOENT");
    });
    it("should handle clean working directory", async () => {
        const { responses, send } = createSendCollector();
        await handleGitDiscard(createRequest({}), send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.error).toBeUndefined();
        expect(resp.payload).toBeDefined();
        expect(resp.payload.discarded).toBe(0);
    });
    it("should error for non-git directory", async () => {
        const nonGitDir = join(tempDir, "not-a-repo");
        await mkdir(nonGitDir);
        closeDatabase();
        openDatabase(dbPath);
        const nonGitProject = createProject("non-git-project", nonGitDir);
        const msg = {
            type: "git_discard",
            requestId: "req-2",
            sessionId: nonGitProject.project_id,
            payload: {},
        };
        const { responses, send } = createSendCollector();
        await handleGitDiscard(msg, send);
        expect(responses).toHaveLength(1);
        const resp = responses[0];
        expect(resp.payload).toBeUndefined();
        expect(resp.error).toBeDefined();
        expect(resp.error.code).toBe(ErrorCode.GIT_NOT_INITIALIZED);
    });
    it("should return error for non-existent project", async () => {
        const msg = {
            type: "git_discard",
            requestId: "req-3",
            sessionId: "non-existent-project-id",
            payload: {},
        };
        const { responses, send } = createSendCollector();
        await handleGitDiscard(msg, send);
        expect(responses).toHaveLength(1);
        expect(responses[0].error).toBeDefined();
        expect(responses[0].error.code).toBe(ErrorCode.INVALID_REQUEST);
    });
});
//# sourceMappingURL=git-discard.test.js.map