@page "/Category/{CategoryName}"
@using Microsoft.EntityFrameworkCore
@using Wave.Data
@using System.Net
@using Microsoft.Extensions.Options

@inject IDbContextFactory<ApplicationDbContext> ContextFactory
@inject IOptions<Customization> Customizations
@inject IOptions<Features> Features
@inject IStringLocalizer<CategoryView> Localizer

<HeadContent>
	@if (Features.Value.Rss && Category is not null) { 
		<link rel="alternate" type="application/rss+xml" title="RSS Feed on @Customizations.Value.AppName | @Category.Name" href="/rss/rss.xml?category=@WebUtility.UrlEncode(Category.Name)">
		<link rel="alternate" type="application/atom+xml" title="Atom RSS Feed on @Customizations.Value.AppName | @Category.Name" href="/rss/atom.xml?category=@WebUtility.UrlEncode(Category.Name)">
	}
	@if (Category is null) {
		<meta name="robots" content="noindex">
	}
</HeadContent>

<PageTitle>@($"{Category?.Name ?? "Not Found"} {TitlePostfix}")</PageTitle>

@if (Category is null) {
	<h1 class="text-3xl lg:text-5xl font-light mb-6 text-primary">@Localizer["NotFound_Title"]</h1>
	<p class="my-3">@Localizer["NotFound_Description"]</p>
	<a class="btn btn-primary" href="/">@Localizer["NotFound_BackToHome_Label"]</a>
} else {
	<h1 class="text-3xl lg:text-5xl font-light mb-6 text-primary">@Localizer["Title"] - @Category.Name</h1>

	<ArticleCardList Articles="Category.Articles.Where(a => !a.IsDeleted && a.PublishDate <= DateTimeOffset.Now).ToList()" />
}

@code {
	[CascadingParameter(Name = "TitlePostfix")]
	private string TitlePostfix { get; set; } = default!;

	[Parameter]
	public string CategoryName { get; set; } = string.Empty;
	private Category? Category { get; set; }

	protected override async Task OnInitializedAsync() {
		await using var context = await ContextFactory.CreateDbContextAsync();
		string category = WebUtility.UrlDecode(CategoryName);
		if (Category != null) return;

		Category = await context.Set<Category>()
			.IgnoreAutoIncludes()
			.Include(c => c.Articles).ThenInclude(a => a.Categories)
			.Include(c => c.Articles).ThenInclude(a => a.Author)
			.AsSplitQuery()
			.FirstOrDefaultAsync(c => c.Name == category);
	}
}
