/*
 *                                      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";
import { type CpanelPage } from "@page/cpanel/cpanel";
import { type Locator } from "@playwright/test";

// plugin lifecycle
const UNINSTALL_XOVI =
    "/usr/local/cpanel/scripts/run_plugin_lifecycle --plugin cpanel-xovi-plugin --method uninstall || true";

// systemctl
const SERVICE_NAME = "initialize_xovi_plugin";
const START_SERVICE = `systemctl start ${SERVICE_NAME}.service`;
const START_TIMER = `systemctl start ${SERVICE_NAME}.timer`;
const IS_TIMER_ACTIVE = `systemctl is-active ${SERVICE_NAME}.timer`;

const xoviLocators = (cpanelPage: CpanelPage): Record<string, Locator> => ({
    mainMenu: cpanelPage.page.locator("#cpanel-xovi-plugin-main-menu"),
    seaOfIcons: cpanelPage.page.locator("#item_cpanel-xovi-plugin"),
});

test.afterAll(async ({ rootSSH }) => {
    await rootSSH.execCommand(START_TIMER);
    await rootSSH.execCommand(START_SERVICE);
});

test.describe("Plugins will re-initialize when they get licensed", () => {
    test.beforeEach(async ({ rootSSH }) => {
        const uninstallResult = await rootSSH.execCommand(UNINSTALL_XOVI);
        expect(uninstallResult.code, "The return code should be 0").toBe(0);
    });

    test("Plugin is not initialized if the service is not triggered yet", async ({
        cpanelPage,
    }) => {
        await expect(
            xoviLocators(cpanelPage).mainMenu,
            "SEO link is not present in cPanel main menu"
        ).toBeHidden();
        await expect(
            xoviLocators(cpanelPage).seaOfIcons,
            "SEO link is not present in sea of icons"
        ).toBeHidden();
    });

    test("Plugin is initialized after the service is started", async ({
        rootSSH,
        cpanelPage,
    }) => {
        const startService = await rootSSH.execCommand(START_SERVICE);
        expect(startService.code, "The return code should be 0").toBe(0);

        const isTimerActive = await rootSSH.execCommand(IS_TIMER_ACTIVE);
        expect(isTimerActive.stdout).toBe("active");

        await cpanelPage.page.reload();

        await expect(
            xoviLocators(cpanelPage).mainMenu,
            "SEO link is present in cPanel main menu"
        ).toBeVisible();
        await expect(
            xoviLocators(cpanelPage).seaOfIcons,
            "SEO link is present in sea of icons"
        ).toBeVisible();
    });
});
