using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using TaxBaik.Application.Services;
using TaxBaik.Domain.Entities;
using TaxBaik.Web.Services;

namespace TaxBaik.Web.Pages.Portal;

[Authorize(AuthenticationSchemes = PortalAuthDefaults.Scheme)]
public class IndexModel : PageModel
{
    private readonly TaxFilingService _taxFilingService;
    private readonly ConsultingActivityService _consultingActivityService;
    private readonly ClientService _clientService;

    public IndexModel(
        TaxFilingService taxFilingService,
        ConsultingActivityService consultingActivityService,
        ClientService clientService)
    {
        _taxFilingService = taxFilingService;
        _consultingActivityService = consultingActivityService;
        _clientService = clientService;
    }

    public TaxBaik.Domain.Entities.Client? ClientInfo { get; private set; }
    public List<TaxFiling> Filings { get; private set; } = new();
    public List<ConsultingActivity> Consultations { get; private set; } = new();

    public async Task<IActionResult> OnGetAsync()
    {
        var clientIdClaim = User.FindFirst("client_id");
        if (clientIdClaim != null && int.TryParse(clientIdClaim.Value, out var clientId))
        {
            ClientInfo = await _clientService.GetByIdAsync(clientId);
            if (ClientInfo != null)
            {
                var filingsData = await _taxFilingService.GetByClientIdAsync(clientId);
                Filings = filingsData.OrderBy(f => f.DueDate).ToList();

                var consultationsData = await _consultingActivityService.GetByClientIdAsync(clientId);
                Consultations = consultationsData.OrderByDescending(c => c.ActivityDate).ToList();
            }
        }
        return Page();
    }
}
