import { promises as fs } from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { getWorkspaceWatchCountForTests, unwatchWorkspaceFile, watchWorkspaceFile, } from './workspace-watch.js';
describe('workspace file watch service', () => {
    let tempRoot = '';
    let workspacePath = '';
    let filePath = '';
    beforeEach(async () => {
        tempRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'aws-workspace-watch-'));
        workspacePath = path.join(tempRoot, 'workspace');
        filePath = path.join(workspacePath, 'demo.docx');
        await fs.mkdir(workspacePath, { recursive: true });
        await fs.writeFile(filePath, 'watch me', 'utf-8');
    });
    afterEach(async () => {
        await unwatchWorkspaceFile({ workspacePath, filePath }).catch(() => undefined);
        await unwatchWorkspaceFile({ workspacePath, filePath }).catch(() => undefined);
        await fs.rm(tempRoot, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 });
    });
    it('unwatches a deleted file by its original workspace path key', async () => {
        await watchWorkspaceFile({ workspacePath, filePath });
        expect(getWorkspaceWatchCountForTests()).toBe(1);
        await fs.rm(filePath);
        await unwatchWorkspaceFile({ workspacePath, filePath });
        expect(getWorkspaceWatchCountForTests()).toBe(0);
    });
    it('keeps shared watchers until all references unwatch', async () => {
        await watchWorkspaceFile({ workspacePath, filePath });
        await watchWorkspaceFile({ workspacePath, filePath });
        expect(getWorkspaceWatchCountForTests()).toBe(1);
        await unwatchWorkspaceFile({ workspacePath, filePath });
        expect(getWorkspaceWatchCountForTests()).toBe(1);
        await unwatchWorkspaceFile({ workspacePath, filePath });
        expect(getWorkspaceWatchCountForTests()).toBe(0);
    });
});
