namespace SteUp.Maui;

public partial class MainPage : ContentPage
{
    private static readonly string AttachedDir =
        Path.Combine(FileSystem.CacheDirectory, "attached");

    private const string Prefix = "https://localfiles/attached/";

    public MainPage()
    {
        InitializeComponent();

        Directory.CreateDirectory(AttachedDir);

        BlazorWebView.WebResourceRequested += BlazorWebView_WebResourceRequested;
    }

    private static void BlazorWebView_WebResourceRequested(object? sender, WebViewWebResourceRequestedEventArgs e)
    {
        var uri = e.Uri.ToString();
        if (string.IsNullOrWhiteSpace(uri) ||
            !uri.StartsWith(Prefix, StringComparison.OrdinalIgnoreCase))
            return;

        var fileName = uri[Prefix.Length..];

        fileName = fileName.Replace("\\", "/");
        if (fileName.Contains("..") || fileName.Contains('/'))
        {
            e.Handled = true;
            e.SetResponse(400, "Bad Request");
            return;
        }

        var fullPath = Path.Combine(AttachedDir, fileName);

        if (!File.Exists(fullPath))
        {
            e.Handled = true;
            e.SetResponse(404, "Not Found");
            return;
        }

        e.Handled = true;
        e.SetResponse(200, "OK", GetContentType(fullPath), File.OpenRead(fullPath));
    }

    private static string GetContentType(string path)
    {
        return Path.GetExtension(path).ToLowerInvariant() switch
        {
            ".png" => "image/png",
            ".jpg" or ".jpeg" => "image/jpeg",
            ".webp" => "image/webp",
            _ => "application/octet-stream"
        };
    }
}