/*
 *                                      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";

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

export const test = baseTest.extend<CompanyIDFixtures>({
    CID: async ({ rootSSH, server }, use, testInfo) => {
        const CID_PATH = "/var/cpanel/companyid.fast";
        // Read the current company ID
        const readCidLink = await rootSSH.execCommand(`readlink ${CID_PATH}`);
        if (readCidLink.code > 0) {
            throw new Error(`Failed to read CID link from file ${CID_PATH}`);
        }

        const originalCID = Number(readCidLink.stdout);
        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";
