using SharedKernel.Extensions;
using SharedKernel.Helpers;
using Application.Abstractions.Messaging;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Admin.Pages.Crypto.News
{
    public class IndexModel(IMediator mediator) : PageModel
    {
        [BindProperty(SupportsGet = true)]
        public QueryParams Query { get; set; } = new();

        public sealed class QueryParams
        {
            [Range(1, int.MaxValue)]
            [DisplayName("페이지 번호")]
            public int PageNum { get; set; } = 1;

            [Range(1, 100)]
            [DisplayName("페이지 당 수")]
            public ushort PerPage { get; set; } = 20;
        }

        public int Total { get; set; }

        public List<(
            int Num,
            int ID,
            string Name,
            string Url,
            string? Description,
            int IntervalMinutes,
            char IsActive,
            string? LastFetchedAt,
            string CreatedAt,
            string EditURL
        )> List { get; set; } = [];

        public Pagination? Pagination { get; set; }

        public async Task OnGetAsync(CancellationToken ct)
        {
            if (!ModelState.IsValid)
            {
                return;
            }

            var result = await mediator.Send(new SearchNewsSources.Query(
                Query.PageNum,
                Query.PerPage
            ), ct);

            Total = result.Total;

            List = [..result.List.Select(c => (
                c.Num,
                c.ID,
                c.Name,
                c.Url,
                c.Description,
                c.IntervalMinutes,
                c.IsActive ? 'Y' : 'N',
                c.LastFetchedAt.GetDateAt() ?? "-",
                c.CreatedAt.GetDateAt(),
                EditURL: $"/Crypto/News/Edit/{c.ID}{Request.QueryString}"
            ))];

            Pagination = new Pagination(result.Total, Query.PageNum, Query.PerPage);
        }

        public async Task<IActionResult> OnPostDeleteAsync(int[] ids, CancellationToken ct)
        {
            try
            {
                await mediator.Send(new DeleteNewsSource.Command(ids), ct);

                TempData["SuccessMessage"] = $"{ids.Length}개 소스가 삭제되었습니다.";
            }
            catch (Exception e)
            {
                TempData["ErrorMessages"] = e.Message;
            }

            return RedirectToPage("/Crypto/News/Index", Query);
        }

        public async Task<IActionResult> OnPostForceFetchAsync(int id, CancellationToken ct)
        {
            try
            {
                var count = await mediator.Send(new ForceFetchNewsSource.Command(id), ct);

                TempData["SuccessMessage"] = $"강제 수집 완료: {count}건 수집되었습니다.";
            }
            catch (Exception e)
            {
                TempData["ErrorMessages"] = e.Message;
            }

            return RedirectToPage("/Crypto/News/Index", Query);
        }
    }
}