using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using TaxBaik.Application.Services;
using TaxBaik.Web.Services;

namespace TaxBaik.Web.Pages.Admin.Clients;

[Authorize(AuthenticationSchemes = AdminAuthDefaults.Scheme)]
public class IndexModel(ClientService clientService) : PageModel
{
    public List<TaxBaik.Domain.Entities.Client> Items { get; private set; } = [];
    public int CurrentPage { get; private set; } = 1;
    public int TotalPages { get; private set; } = 1;
    public int TotalCount { get; private set; }
    public string? Search { get; set; }
    public string? Status { get; set; }
    public int PageSize { get; set; } = 10;

    public async Task OnGetAsync(string? search, string? status, int page = 1, int pageSize = 10, CancellationToken ct = default)
    {
        Search = search;
        Status = status;
        PageSize = pageSize;
        CurrentPage = Math.Max(1, page);

        var (items, total) = await clientService.GetPagedAsync(CurrentPage, PageSize, status, search, ct);
        Items = items.ToList();
        TotalCount = total;
        TotalPages = Math.Max(1, (int)Math.Ceiling(total / (double)PageSize));
    }

    public string BuildPageUrl(int page) =>
        $"/admin/clients?search={Uri.EscapeDataString(Search ?? string.Empty)}&status={Uri.EscapeDataString(Status ?? string.Empty)}&page={page}&pageSize={PageSize}";

    public async Task<IActionResult> OnPostDeleteAsync(int id, CancellationToken ct)
    {
        await clientService.DeleteAsync(id, ct);
        return RedirectToPage();
    }
}
