using Microsoft.AspNetCore.Mvc.RazorPages;
using TaxBaik.Application.Seasonal;
using TaxBaik.Application.Services;
using TaxBaik.Domain.Entities;

namespace TaxBaik.Web.Pages;

public class IndexModel : PageModel
{
    private readonly BlogService _blogService;
    private readonly SeasonalMarketingService _seasonalMarketingService;
    private readonly AnnouncementService _announcementService;
    private readonly FaqService _faqService;

    public List<BlogPost> RecentPosts { get; set; } = [];
    public List<BlogPost> SeasonalPosts { get; set; } = [];
    public CurrentSeasonDto? CurrentSeason { get; set; }
    public List<Announcement> ActiveAnnouncements { get; set; } = [];
    public List<Faq> ActiveFaqs { get; set; } = [];

    public IndexModel(
        BlogService blogService,
        SeasonalMarketingService seasonalMarketingService,
        AnnouncementService announcementService,
        FaqService faqService)
    {
        _blogService = blogService;
        _seasonalMarketingService = seasonalMarketingService;
        _announcementService = announcementService;
        _faqService = faqService;
    }

    public async Task OnGetAsync()
    {
        CurrentSeason = _seasonalMarketingService.GetCurrentSeason();

        var announcementsTask = LoadSafeAsync(() => _announcementService.GetActiveAsync());
        var faqsTask = LoadSafeAsync(() => _faqService.GetActiveAsync());
        var blogTask = LoadBlogAsync();

        await Task.WhenAll(announcementsTask, faqsTask, blogTask);

        ActiveAnnouncements = (await announcementsTask)?.ToList() ?? [];
        ActiveFaqs = (await faqsTask)?.ToList() ?? [];
    }

    private async Task LoadBlogAsync()
    {
        try
        {
            if (CurrentSeason is not null && !string.IsNullOrEmpty(CurrentSeason.RelatedCategorySlug))
            {
                var (seasonal, latest) = await _blogService.GetSeasonalPostsAsync(
                    CurrentSeason.RelatedCategorySlug, seasonalCount: 2, totalCount: 3);
                SeasonalPosts = seasonal.ToList();
                RecentPosts = latest.ToList();
            }
            else
            {
                var (posts, _) = await _blogService.GetPublishedPagedAsync(1, 3);
                RecentPosts = posts.ToList();
            }
        }
        catch
        {
            RecentPosts = [];
            SeasonalPosts = [];
        }
    }

    private static async Task<IEnumerable<T>?> LoadSafeAsync<T>(Func<Task<IEnumerable<T>>> loader)
    {
        try { return await loader(); }
        catch { return null; }
    }
}
