using DeepDrftModels.DTOs;
using DeepDrftModels.Enums;
using DeepDrftPublic.Client.Services;
using Microsoft.AspNetCore.Components;

namespace DeepDrftPublic.Client.Pages;

/// <summary>
/// Shared fetch + prerender-bridge logic for the medium browse pages (Sessions, Mixes). Subclasses
/// supply only the <see cref="Medium"/> and <see cref="DetailRoute"/>; this base fetches the paged
/// releases and bridges the prerendered result across the prerender -> WASM seam so the WASM pass
/// does not re-fetch and replay the card animations.
/// </summary>
public abstract class MediumBrowseBase : ComponentBase, IDisposable
{
    [Inject] public required IReleaseDataService ReleaseData { get; set; }
    [Inject] public required PersistentComponentState PersistentState { get; set; }

    /// <summary>The medium this page browses. Subclass-supplied constant.</summary>
    protected abstract ReleaseMedium Medium { get; }

    protected bool Loading { get; private set; } = true;
    protected IReadOnlyList<ReleaseDto> Releases { get; private set; } = [];

    private PersistingComponentStateSubscription _persistingSubscription;

    private string PersistKey => $"medium-browse-{Medium}";

    protected override async Task OnInitializedAsync()
    {
        _persistingSubscription = PersistentState.RegisterOnPersisting(Persist);

        if (PersistentState.TryTakeFromJson<List<ReleaseDto>>(PersistKey, out var restored) && restored is not null)
        {
            Releases = restored;
            Loading = false;
            return;
        }

        var result = await ReleaseData.GetPaged(Medium.ToString().ToLowerInvariant(), page: 1, pageSize: 100);
        if (result is { Success: true, Value: { Items: { } items } })
            Releases = items.ToList();

        Loading = false;
    }

    private Task Persist()
    {
        if (Releases.Count > 0)
            PersistentState.PersistAsJson(PersistKey, Releases.ToList());
        return Task.CompletedTask;
    }

    public void Dispose() => _persistingSubscription.Dispose();
}
