namespace AuthorBuddy.Web.Models;

public static class ProjectPathHelper
{
    public static string AllowedBasePath =>
        Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
            "AuthorBuddy"
        );

    public static bool IsPathAllowed(string path)
    {
        if (string.IsNullOrWhiteSpace(path)) return false;
        var full = Path.GetFullPath(path);
        var allowed = Path.GetFullPath(AllowedBasePath);
        return full.StartsWith(allowed + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)
            || string.Equals(full, allowed, StringComparison.OrdinalIgnoreCase);
    }

    public static string SuggestPath(string projectName)
    {
        var safeName = Sanitize(projectName);
        return Path.Combine(AllowedBasePath, safeName);
    }

    private static string Sanitize(string name)
    {
        var invalid = Path.GetInvalidFileNameChars();
        var result = new string(name.Where(c => !invalid.Contains(c)).ToArray());
        return string.IsNullOrWhiteSpace(result) ? "Projekt" : result.Trim();
    }
}
