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

const uuidRegex = /^\w{8}(?:-\w{4}){3}-\w{12}$/;

let pluginsUUIDFile: string;
test.beforeAll(async ({ workerCpanelAccount, rootSSH }) => {
    pluginsUUIDFile =
        (await workerCpanelAccount.getHomeDirectory()) + "/.cpanel/plugin_uuid";
    await rootSSH.delete(pluginsUUIDFile);
});

test.afterAll(async ({ rootSSH }) => {
    await rootSSH.delete(pluginsUUIDFile);
});

test("Plugins::reset_uuid creates or replaces a UUID", async ({
    workerCpanelAccount,
    uapiResponseTemplate,
    rootSSH,
    rootSFTP,
}) => {
    let result = await workerCpanelAccount.uapi.call("Plugins", "reset_uuid");
    expect(
        result.raw,
        "Plugins::reset_uuid returns a uuid and success"
    ).toEqual(
        uapiResponseTemplate({
            data: { uuid: expect.stringMatching(uuidRegex) },
        })
    );
    expect(
        await rootSSH.fileExists(pluginsUUIDFile),
        "The plugin_uuid file was created"
    ).toBeTruthy();
    const firstUUID = (await rootSFTP.get(pluginsUUIDFile)).toString();
    expect(
        firstUUID,
        "The uuid is returned by reset_uuid matches the plugins_uuid file"
    ).toBe(result.data.uuid);

    result = await workerCpanelAccount.uapi.call("Plugins", "reset_uuid");
    expect(
        result.raw,
        "Plugins::reset_uuid returns returns a valid uuid and a success"
    ).toEqual(
        uapiResponseTemplate({
            data: { uuid: expect.stringMatching(uuidRegex) },
        })
    );
    expect(
        result.data.uuid,
        "A new UUID was generated and it is NOT the same as the first"
    ).not.toBe(firstUUID);
    expect(
        (await rootSFTP.get(pluginsUUIDFile)).toString(),
        "The uuid returned by reset_uuid matches the plugins_uuid file"
    ).toBe(result.data.uuid);
});
