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

namespace Admin.Pages.Crypto.News
{
    public class WriteModel(IMediator mediator) : PageModel
    {
        [BindProperty]
        public InputModel Input { get; set; } = new();

        public sealed class InputModel
        {
            [Required(ErrorMessage = "이름은 필수입니다.")]
            [StringLength(200, ErrorMessage = "이름은 {1}자 이하로 입력하세요.")]
            public string Name { get; set; } = null!;

            [Required(ErrorMessage = "URL은 필수입니다.")]
            [StringLength(2048, ErrorMessage = "URL은 {1}자 이하로 입력하세요.")]
            [DataType(DataType.Url)]
            public string Url { get; set; } = null!;

            [StringLength(500, ErrorMessage = "설명은 {1}자 이하로 입력하세요.")]
            public string? Description { get; set; }

            [Range(1, 1440, ErrorMessage = "수집주기는 1~1440분 사이로 입력하세요.")]
            public int IntervalMinutes { get; set; } = 10;
        }

        public void OnGet()
        {
        }

        public async Task<IActionResult> OnPostAsync(CancellationToken ct)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    throw new Exception(ModelState.GetErrorMessages());
                }

                await mediator.Send(new CreateNewsSource.Command(
                    Input.Name,
                    Input.Url,
                    Input.Description,
                    Input.IntervalMinutes
                ), ct);

                TempData["SuccessMessage"] = $"{Input.Name} 소스가 등록되었습니다.";

                return RedirectToPage("/Crypto/News/Index");
            }
            catch (Exception e)
            {
                TempData["ErrorMessages"] = e.Message;

                return RedirectToPage("/Crypto/News/Write");
            }
        }
    }
}