// (C) 2021-2023 GoodData Corporation
const {
    createTigerWorkspaceWithPrefix,
    defaultScanPublishPDMForDatasource,
    setTigerWorkspaceLayoutFromFixtures
} = require('./fixture_tiger');

const { log, logLn } = require('./logger');

async function createWorkspaceFromFixture(
    workspacePrefix, fixtureType, dataSource, token, host, backend, metadataExtension
) {
    const workspaceId = await createTigerWorkspaceWithPrefix(workspacePrefix, token, host, backend);
    await defaultScanPublishPDMForDatasource(dataSource, token, host, backend);

    logLn(
        `Creating fixture. Type: ${fixtureType}, datasource: ${dataSource}, additional md objects: ${metadataExtension}`,
    );
    await setTigerWorkspaceLayoutFromFixtures(
        workspaceId,
        fixtureType,
        dataSource,
        token,
        host,
        backend,
        metadataExtension,
    );
    return workspaceId;
}

async function createTigerReferenceWorkspace(
    host,
    tigerApiToken,
    testWorkspaceId,
    tigerDatasourceName,
    fixtureType = 'goodsales',
    sdkBackend,
    metadataExtension,
    workspaceNamePrefix,
) {
    if (testWorkspaceId) {
        log(
            `WORKSPACE_ID ${testWorkspaceId} is already present. Delete the workspace by running delete_tiger_workspace.js or remove the the record in  .env\n`,
        );
        return undefined;
    }

    if (!(host && tigerApiToken)) {
        log('HOST, TIGER_API_TOKEN need to be set\n');
        return undefined;
    }

    if (!(tigerDatasourceName && fixtureType)) {
        log('TIGER_DATASOURCES_NAME, FIXTURE_TYPE need to be set\n');
        return undefined;
    }

    const testReferenceWorkspaceId = await createWorkspaceFromFixture(
        workspaceNamePrefix,
        fixtureType,
        tigerDatasourceName,
        tigerApiToken,
        host,
        sdkBackend,
        metadataExtension
    );
    return testReferenceWorkspaceId;
}

module.exports = {
    createWorkspaceFromFixture,
    createTigerReferenceWorkspace
};
