@using Microsoft.EntityFrameworkCore
@using OpenArchival.DataAccess
@using MudBlazor
@using OpenArchival.Blazor.ArtifactGroupingDisplay

@namespace OpenArchival.Blazor.ArchiveDisplay

<MudPaper Class="pa-4 ma-2 rounded" Elevation="3" Style="overflow-x:auto">
    <MudText Typo="Typo.h6">@SliderEntry.Title</MudText>
    <MudDivider/>
    @if (!string.IsNullOrEmpty(SliderEntry.Description))
    {
        <MudText Typo="Typo.caption">@SliderEntry.Description</MudText>
    }
    <MudStack Row="true" Spacing="4" Style="flex-wrap: nowrap;">
        @foreach (ArtifactGrouping grouping in ArtifactGroupings)
        {
            <div style="min-width: 300px;">
                <ArtifactGroupingSearchResult ArtifactGrouping="grouping" Height="300"></ArtifactGroupingSearchResult>
            </div>
        }
    </MudStack>
</MudPaper>


@inject IDbContextFactory<ApplicationDbContext> ContextFactory;
@code {
    [Parameter]
    public required SearchPageSliderEntry SliderEntry { get; set; }

    private List<ArtifactGrouping> ArtifactGroupings { get; set; } = [];

    protected override async Task OnParametersSetAsync()
    {
        await using var context = await ContextFactory.CreateDbContextAsync();

        // First, handle the case where there are no tags to filter by.
        if (SliderEntry.FilterTags == null || !SliderEntry.FilterTags.Any())
        {
            ArtifactGroupings = new List<ArtifactGrouping>();
            return;
        }

        // It's much more efficient to get the IDs of the tags first.
        var requiredTagIds = SliderEntry.FilterTags.Select(t => t.Id).ToList();
        int requiredTagCount = requiredTagIds.Count;

        ArtifactGroupings = await context.ArtifactGroupings
            .Include(g => g.ChildArtifactEntries)
                .ThenInclude(e => e.Tags)
            .Include(g=>g.ChildArtifactEntries)
                .ThenInclude(e=>e.Files)
            .Where(grouping =>
                grouping.ChildArtifactEntries.Any(entry =>
                    entry.Tags.Count(tag => requiredTagIds.Contains(tag.Id)) == requiredTagCount
                )
            )
            // AsSplitQuery() is a performance optimization for complex queries with multiple Includes.
            .AsSplitQuery()
            .ToListAsync();

        StateHasChanged();
    }
}
