import {createResolvers} from "../api/resolvers.js";
import {zabbixAPI} from "../datasources/zabbix-api.js";
import {Permission} from "../schema/generated/graphql.js";

// Mocking ZabbixAPI
jest.mock("../datasources/zabbix-api.js", () => ({
    zabbixAPI: {
        executeRequest: jest.fn(),
        post: jest.fn(),
        getVersion: jest.fn(),
        baseURL: "http://mock-zabbix"
    }
}));

describe("Zabbix 6.0 Compatibility", () => {
    let resolvers: any;

    beforeEach(() => {
        jest.clearAllMocks();
        resolvers = createResolvers();
        (zabbixAPI.getVersion as jest.Mock).mockResolvedValue("6.0.0");
    });

    test("importUserRights uses name-based fallback for host groups on Zabbix 6.0", async () => {
        // Mock Zabbix 6.0 behavior where hostgroup.get does NOT return UUID
        (zabbixAPI.post as jest.Mock).mockImplementation((path: string) => {
            if (path === "templategroup.get") return Promise.resolve([{ groupid: "101", name: "TemplateGroup1", uuid: "uuid-tg-1" }]);
            if (path === "hostgroup.get") return Promise.resolve([{ groupid: "201", name: "HostGroup1" }]); // NO UUID
            if (path === "usergroup.get") return Promise.resolve([]);
            if (path.startsWith("usergroup.create")) return Promise.resolve({ usrgrpids: ["301"] });
            if (path === "module.get") return Promise.resolve([]);
            if (path === "role.get") return Promise.resolve([]);
            return Promise.resolve([]);
        });

        const args = {
            input: {
                userGroups: [{
                    name: "NewGroup",
                    hostgroup_rights: [{
                        name: "HostGroup1",
                        uuid: "some-uuid-from-export", // This UUID won't match anything in 6.0 mock
                        permission: Permission.Read
                    }]
                }]
            },
            dryRun: false
        };
        const context = { zabbixAuthToken: "test-token" };

        const result = await resolvers.Mutation.importUserRights(null, args, context);

        expect(result.userGroups).toHaveLength(1);
        expect(result.userGroups[0].name).toBe("NewGroup");
        expect(result.userGroups[0].errors).toHaveLength(0); // Should succeed via name match
        
        // Verify that usergroup.create was called with correct groupid from name match
        const createCall = (zabbixAPI.post as jest.Mock).mock.calls.find(call => call[0].startsWith("usergroup.create"));
        expect(createCall[1].body.params.rights).toContainEqual({
            id: 201,
            permission: Permission.Read
        });
    });

    test("importUserRights performs manual expansion on Zabbix 6.0", async () => {
        // Mock Zabbix 6.0 behavior
        (zabbixAPI.post as jest.Mock).mockImplementation((path: string, options: any) => {
            if (path === "templategroup.get") return Promise.resolve([]);
            if (path === "hostgroup.get") {
                // If searching for subgroups
                if (options?.body?.params?.search?.name === "Parent/*") {
                    return Promise.resolve([{ groupid: "202", name: "Parent/Child" }]);
                }
                return Promise.resolve([{ groupid: "201", name: "Parent" }]);
            }
            if (path === "usergroup.get") return Promise.resolve([]);
            if (path.startsWith("usergroup.create")) return Promise.resolve({ usrgrpids: ["301"] });
            if (path === "module.get") return Promise.resolve([]);
            if (path === "role.get") return Promise.resolve([]);
            return Promise.resolve([]);
        });

        const args = {
            input: {
                userGroups: [{
                    name: "NewGroup",
                    hostgroup_rights: [{
                        name: "Parent",
                        uuid: "uuid-parent",
                        permission: Permission.Read
                    }]
                }]
            },
            dryRun: false
        };
        const context = { zabbixAuthToken: "test-token" };

        await resolvers.Mutation.importUserRights(null, args, context);

        // Verify that usergroup.create was called with both parent and expanded child
        const createCall = (zabbixAPI.post as jest.Mock).mock.calls.find(call => call[0].startsWith("usergroup.create"));
        expect(createCall[1].body.params.rights).toHaveLength(2);
        expect(createCall[1].body.params.rights).toContainEqual({ id: 201, permission: Permission.Read });
        expect(createCall[1].body.params.rights).toContainEqual({ id: 202, permission: Permission.Read });
    });
});
