package com.ruoyi.cc.utils;

import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * Resolve FreeSWITCH conf paths under fs_conf_directory with name whitelist + containment.
 */
public final class FsConfPathUtils {

    private FsConfPathUtils() {
    }

    public static Path resolveSipProfilesBase(String fsConfDirectory) {
        if (fsConfDirectory == null || fsConfDirectory.isEmpty()) {
            return null;
        }
        return Paths.get(fsConfDirectory, "sip_profiles").toAbsolutePath().normalize();
    }

    public static Path resolveTemplateBase(String fsConfDirectory) {
        if (fsConfDirectory == null || fsConfDirectory.isEmpty()) {
            return null;
        }
        return Paths.get(fsConfDirectory, "template").toAbsolutePath().normalize();
    }

    /**
     * sip_profiles/{profileName}.xml
     */
    public static Path resolveProfileXml(String fsConfDirectory, String profileName) {
        if (!FsEslNameUtils.isSafeName(profileName)) {
            return null;
        }
        Path base = resolveSipProfilesBase(fsConfDirectory);
        if (base == null) {
            return null;
        }
        Path file = base.resolve(profileName + ".xml").normalize();
        return file.startsWith(base) ? file : null;
    }

    /**
     * sip_profiles/{profileName}/
     */
    public static Path resolveProfileDir(String fsConfDirectory, String profileName) {
        if (!FsEslNameUtils.isSafeName(profileName)) {
            return null;
        }
        Path base = resolveSipProfilesBase(fsConfDirectory);
        if (base == null) {
            return null;
        }
        Path dir = base.resolve(profileName).normalize();
        return dir.startsWith(base) ? dir : null;
    }

    /**
     * sip_profiles/{profileName}/{gwName}.xml
     */
    public static Path resolveGatewayXml(String fsConfDirectory, String profileName, String gwName) {
        if (!FsEslNameUtils.isSafeName(profileName) || !FsEslNameUtils.isSafeName(gwName)) {
            return null;
        }
        Path dir = resolveProfileDir(fsConfDirectory, profileName);
        if (dir == null) {
            return null;
        }
        Path file = dir.resolve(gwName + ".xml").normalize();
        return file.startsWith(dir) ? file : null;
    }

    /**
     * template/{templateName}.xml (profileType or MRWG0/MRWG1)
     */
    public static Path resolveTemplateXml(String fsConfDirectory, String templateName) {
        if (!FsEslNameUtils.isSafeName(templateName)) {
            return null;
        }
        Path base = resolveTemplateBase(fsConfDirectory);
        if (base == null) {
            return null;
        }
        Path file = base.resolve(templateName + ".xml").normalize();
        return file.startsWith(base) ? file : null;
    }
}
