/**
 * Unit tests for requireValidator.
 */
import { jest } from '@jest/globals';

// Capture fs mock so tests can call .mockReturnValue() on it
const mockExistsSync = jest.fn();

// Mock 'fs' BEFORE importing any module that depends on it
await jest.unstable_mockModule('fs', () => ({
    existsSync: mockExistsSync
}));

const { validateRequire } = await import("../../../core/src/validators/includeValidator.js");
const { makeDocument, alwaysWarn, alwaysOff, messageIds } = await import("./helpers.js");

describe('validateRequire', () => {
    beforeEach(() => {
        jest.clearAllMocks();
    });

    describe('happy path — no diagnostics', () => {
        test('returns empty array when REQUIRE file exists', () => {
            mockExistsSync.mockReturnValue(true);
            const doc = makeDocument(['REQUIRE mylib.txt'], '/workspace/report.txt');
            expect(validateRequire(doc, alwaysWarn)).toHaveLength(0);
        });

        test('returns empty array for lines without REQUIRE', () => {
            mockExistsSync.mockReturnValue(false);
            const doc = makeDocument(['SET zName = "hello"']);
            expect(validateRequire(doc, alwaysWarn)).toHaveLength(0);
        });

        test('returns empty array for empty document', () => {
            const doc = makeDocument(['']);
            expect(validateRequire(doc, alwaysWarn)).toHaveLength(0);
        });
    });

    describe('ACU-INC-004 — file not found', () => {
        test('flags REQUIRE when file does not exist', () => {
            mockExistsSync.mockReturnValue(false);
            const doc = makeDocument(['REQUIRE missing.txt'], '/workspace/report.txt');
            const diags = validateRequire(doc, alwaysWarn);
            expect(messageIds(diags)).toContain('ACU-INC-004');
        });

        test('diagnostic message contains the missing filename', () => {
            mockExistsSync.mockReturnValue(false);
            const doc = makeDocument(['REQUIRE missing.txt'], '/workspace/report.txt');
            const diags = validateRequire(doc, alwaysWarn);
            expect(diags[0].message).toMatch(/missing\.txt/);
        });

        test('flags multiple missing REQUIRE files', () => {
            mockExistsSync.mockReturnValue(false);
            const doc = makeDocument([
                'REQUIRE lib1.txt',
                'SET x = 1',
                'REQUIRE lib2.txt'
            ], '/workspace/report.txt');
            const diags = validateRequire(doc, alwaysWarn);
            expect(diags).toHaveLength(2);
        });
    });

    describe('severity', () => {
        test('produces no diagnostic when severity is off', () => {
            mockExistsSync.mockReturnValue(false);
            const doc = makeDocument(['REQUIRE missing.txt'], '/workspace/report.txt');
            expect(validateRequire(doc, alwaysOff)).toHaveLength(0);
        });
    });
});
