using Microsoft.AspNetCore.Mvc;

namespace Api;

public static class Program {
  public static void Main(string[] args) {
    var builder = WebApplication.CreateBuilder(args);
    var app = builder.Build();

    app.MapGet("/api/r/{**file}", async ([FromRoute] string file) => {
      if (!ValidEpisode(file)) return Results.BadRequest();
      try {
        var link = await new B2ApiClient().GetDownloadLink(file);
        return Results.Json(link);
      } catch (Exception ex) {
        Console.WriteLine("Error fetching download link");
        Console.WriteLine($"{ex.GetType().Name}: {ex.Message}");
        Console.WriteLine(ex.StackTrace);
        return Results.Problem();
      }
    });

    app.Run();
  }

  private static bool ValidEpisode(string file) {
    return file.StartsWith("otr/", StringComparison.InvariantCulture)
        && file.Split('/').Length == 3;
  }
}
