/*
 *                                      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 as baseTest, type cpanelFixtures } from "@fixtures/cpanel/cpanel";
import logger from "@lib/winston";
import { type SSH } from "@classes/ssh";

/**
 * See also Sitejet's config for it's company ID handling:
 * cpanel/sitejet/perl/usr/local/cpanel/t/qa/playwright/classes/plugins/sitejet/config.ts
 */

type CompanyIDFixtures = cpanelFixtures & {
    CID: number;
};

/**
 * Read the current company ID from the server using readLink
 * TODO: DUCKS-3356 - consolidate with ULC's version
 *
 * @param ssh - SSH connection to the server
 * @returns The current company ID as a number
 */
export async function getCompanyId(ssh: SSH): Promise<number> {
    const CID_PATH = "/var/cpanel/companyid.fast";
    const readCidLink = await ssh.readLink(CID_PATH);

    const companyId = Number(readCidLink);
    if (isNaN(companyId)) {
        throw new Error(
            `Invalid company ID: ${readCidLink} read from ${CID_PATH}`
        );
    }

    return companyId;
}

/**
 * System for assigning Company IDs, and automatically restores the original.
 * It removes the need to make the assignment before each test, or restore it after.
 */
export const test = baseTest.extend<CompanyIDFixtures>({
    CID: async ({ rootSSH, server }, use, testInfo) => {
        // Read the current company ID using the utility function
        const originalCID = await getCompanyId(rootSSH);
        logger.debug(`Originally configured CID: ${originalCID}`);

        // Extract CID from test tags
        let customCID = 99999; // default

        const cidTag = testInfo.tags.find((tag) => tag.startsWith("@cid-"));
        if (cidTag) {
            const cidValue = cidTag.replace("@cid-", "");
            customCID = Number(cidValue);
        }

        logger.debug(
            `Setting test company ID to: ${customCID} (from tags: ${testInfo.tags})`
        );
        await server.changeCompanyIDset(customCID);

        await use(customCID);

        // Restore original company ID after test
        logger.debug(`Restoring original company ID: ${originalCID}`);
        await server.changeCompanyIDset(originalCID);
    },
});

export { expect } from "@playwright/test";
