const std = @import("std");
const types = @import("../../src/types.zig"); // adjust path
const ManSearcher = @import("../../src/searcher.zig").ManSearcher; // adjust path

const error = error{
    FastFail,
};

test "searchManPagesFast returns dummy entries" {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer gpa.deinit();
    const allocator = gpa.allocator();
    const stderr = std.io.getStdErr().writer();

    // Fake ManSearcher with one dummy entry
    var searcher = ManSearcher.init(allocator);
    defer searcher.deinit();

    const dummy_entry = types.ManEntry{
        .name = try allocator.dupe(u8, "printf"),
        .section = try allocator.dupe(u8, "1"),
        .description = try allocator.dupe(u8, "format and print data"),
        .path = null,
    };
    try searcher.entries.append(dummy_entry);

    try std.testing.expect(searcher.entries.items.len == 1);
    try std.testing.expect(std.mem.eql(u8, searcher.entries.items[0].name, "printf"));
}

test "searchManPages fallback triggers on fast failure" {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer gpa.deinit();
    const allocator = gpa.allocator();
    const stderr = std.io.getStdErr().writer();

    // Fake `searchManPagesFast` that always errors
    fn fakeFast(keyword: []const u8, target_section: ?[]const u8, show_paths: bool,
                verbose: bool, allocator: std.mem.Allocator, stderr: *std.io.Writer) !types.ManEntryList {
        return error.FastFail;
    }

    // Fake `searchManPagesOriginal` that returns a dummy entry
    fn fakeOriginal(keyword: []const u8, target_section: ?[]const u8, show_paths: bool,
                    verbose: bool, allocator: std.mem.Allocator, stderr: *std.io.Writer) !types.ManEntryList {
        var list = types.ManEntryList.init(allocator);
        defer list.deinit();

        const dummy = types.ManEntry{
            .name = try allocator.dupe(u8, "ls"),
            .section = try allocator.dupe(u8, "1"),
            .description = try allocator.dupe(u8, "list directory contents"),
            .path = null,
        };
        try list.append(dummy);

        return list;
    }

    // Mimic the fallback logic from your main function
    const result = fakeFast("ls", null, false, true, allocator, stderr) catch |err| {
        try std.testing.expect(err == error.FastFail);
        return fakeOriginal("ls", null, false, true, allocator, stderr);
    };

    try std.testing.expect(result.items.len == 1);
    try std.testing.expect(std.mem.eql(u8, result.items[0].name, "ls"));
}

