/*
 *                                      Copyright 2025 WebPros International, LLC
 *                                                           All rights reserved.
 * copyright@cpanel.net                                         http://cpanel.net
 * This code is subject to the cPanel license. Unauthorized copying is prohibited.
 */

import { test, expect } from "@fixtures/cpanel/cpanel";

const methodCache = "/var/cpanel/plugins/common/methodcache.json";

test.afterAll(async ({ rootSFTP, server }) => {
    await rootSFTP.delete(methodCache, false);
    await server.changeCompanyIDset(7);
});

test("Plugins::can_show_promotion api call", async ({
    server,
    workerCpanelAccount,
    rootSFTP,
    uapiResponseTemplate,
}) => {
    let response = await workerCpanelAccount.uapi.call(
        "Plugins",
        "can_show_promotions",
        { plugin: "koality" }
    );

    expect(response.raw, "can_show_promotions should be enabled").toEqual(
        uapiResponseTemplate({
            data: {
                can_show_promotions: 1,
            },
        })
    );
    // Clean the cache to avoid getting the previous ID
    await rootSFTP.delete(methodCache);
    // This test assumes it's being performed on OpenStack, which uses cPanel licenses with a company ID of 7. This company ID is on the whitelist.
    await server.changeCompanyIDset(1234);

    response = await workerCpanelAccount.uapi.call(
        "Plugins",
        "can_show_promotions",
        { plugin: "koality" }
    );
    expect(
        await rootSFTP.exists(methodCache),
        `The API generates the cache (${methodCache})`
    ).toBeTruthy();

    expect(
        response.raw,
        "can_show_promotions should be disabled with companyID not on the whitelist. e.g., 1234"
    ).toEqual(
        uapiResponseTemplate({
            data: {
                can_show_promotions: 0,
            },
        })
    );

    response = await workerCpanelAccount.uapi.call(
        "Plugins",
        "can_show_promotions"
    );

    expect(response.raw, "Plugin argument is required").toEqual(
        uapiResponseTemplate({
            errors: ["Provide the “plugin” argument."],
            status: 0,
        })
    );

    response = await workerCpanelAccount.uapi.call(
        "Plugins",
        "can_show_promotions",
        { plugin: "notaplugin" }
    );

    const expectedOutput = uapiResponseTemplate({
        status: 0,
        messages: [
            "Could not load methods for plugin notaplugin. Check notaplugin for validity.",
        ],
        metadata: {},
        data: null,
        errors: expect.arrayContaining([]),
        warnings: null,
    });

    expect(
        response.raw,
        "Could not load methods for non existent plugin"
    ).toEqual(expectedOutput);
});
