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

namespace Admin.Pages.Crypto;

public class TickerConfigModel(IMediator mediator) : PageModel
{
    [BindProperty]
    public InputModel Input { get; set; } = new();

    public sealed class InputModel
    {
        [DisplayName("시세 업데이트 주기 (초)")]
        [Range(1, 300)]
        public int TickerRefreshSeconds { get; set; } = 5;

        [DisplayName("급등 임계값 (%)")]
        [Range(0.1, 100)]
        public decimal SurgeThreshold { get; set; } = 5.0m;

        [DisplayName("급락 임계값 (%)")]
        [Range(-100, -0.1)]
        public decimal PlungeThreshold { get; set; } = -5.0m;

        [DisplayName("메인 페이지 기본 표시 코인 수")]
        [Range(1, 100)]
        public int MainPageCoinCount { get; set; } = 10;
    }

    public async Task OnGetAsync(CancellationToken ct)
    {
        var result = await mediator.Send(new GetTickerConfig.Query(), ct);

        Input = new InputModel
        {
            TickerRefreshSeconds = result.TickerRefreshSeconds,
            SurgeThreshold = result.SurgeThreshold,
            PlungeThreshold = result.PlungeThreshold,
            MainPageCoinCount = result.MainPageCoinCount
        };
    }

    public async Task<IActionResult> OnPostAsync(CancellationToken ct)
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }

        try
        {
            await mediator.Send(new SaveTickerConfig.Command(
                Input.TickerRefreshSeconds,
                Input.SurgeThreshold,
                Input.PlungeThreshold,
                Input.MainPageCoinCount
            ), ct);

            TempData["SuccessMessage"] = "저장되었습니다.";
        }
        catch (Exception e)
        {
            TempData["ErrorMessages"] = e.Message;
        }

        return RedirectToPage("/Crypto/TickerConfig");
    }
}