import path from "path";
import fs from "fs";
import { CItype } from "../../models/models";

function getRepositoryTypeFolder(repositoryType: CItype): string | null {
    switch (repositoryType) {
        case CItype.GITHUB:
            return "github";
        case CItype.DEVOPS:
            return "azure";
        case CItype.GITLAB:
            return "gitlab";
        default:
            return null;
    }
}

export function copyWorkflowFile(
    appPath: string,
    platformtype: string,
    repositoryType: CItype,
    baseURL: string
) {
    const repositoryFolderName = getRepositoryTypeFolder(repositoryType);
    if (!repositoryFolderName) {
        console.log(`Repository type not supported for git action generation.`);
        return;
    }
    console.log("repositoryType : "+repositoryType);
    const sourceFile = path.join(
        __dirname,
        `../../../templates/repository/${repositoryFolderName}/${platformtype}/config.yaml`
    );

    if (!fs.existsSync(sourceFile)) {
        console.log(`Workflow file not found for ${platformtype} and ${repositoryFolderName}`);
        return;
    }

    let destDir: string;
    let destFile: string;
    
    switch (repositoryType) {
        case CItype.GITHUB:
            destDir = path.join(appPath, ".github", "workflows");
            fs.mkdirSync(destDir, { recursive: true });
            destFile = path.join(destDir, "config.yaml");
            break;
        case CItype.DEVOPS:
            destDir = path.join(appPath, "pipeline");
            fs.mkdirSync(destDir, { recursive: true });
            destFile = path.join(destDir, "pipeline.yaml");
            break;
        case CItype.GITLAB:
            destFile = path.join(appPath, ".gitlab-ci.yml");
            break;
        default:
            console.log(`Unsupported repository type for workflow file placement: ${repositoryType}`);
            return;
    }

    fs.copyFileSync(sourceFile, destFile);

    let fileContent = fs.readFileSync(destFile, { encoding: 'utf8' });
    fileContent = fileContent.replace("{{OrdinoURL}}", baseURL);
    fs.writeFileSync(destFile, fileContent);

    console.log(`Workflow file copied for ${platformtype} and ${repositoryFolderName}`);
} 