using SharedKernel;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Options;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Admin.Pages.Document
{
    public class WriteModel(IMediator mediator, IOptions<AppSettings> settings) : PageModel
    {
        public string QueryString { get; private set; } = "";
        public string SiteUrl { get; private set; } = settings.Value.App.FrontURL;

        [BindProperty]
        public InputMdeol Input { get; set; } = new();

        public sealed class InputMdeol
        {
            [DisplayName("주소")]
            [DataType(DataType.Text)]
            [Required(ErrorMessage = "{0}는 필수입니다.")]
            [StringLength(30, ErrorMessage = "{0}은 {1}자 이하로 입력하세요.")]
            [RegularExpression(@"^[a-zA-Z0-9]+$", ErrorMessage = "주소는 영문 및 숫자로만 구성되어야 합니다.")]
            public string Code { get; set; } = default!;

            [DisplayName("제목")]
            [DataType(DataType.Text)]
            [Required(ErrorMessage = "{0}는 필수입니다.")]
            [StringLength(120, ErrorMessage = "{0}은 {1}자 이하로 입력하세요.")]
            public string Subject { get; set; } = default!;

            [DisplayName("내용")]
            [DataType(DataType.Html)]
            public string? Content { get; set; }

            [DisplayName("사용 여부")]
            public bool IsActive { get; set; } = false;
        }

        public Task OnGetAsync(CancellationToken _)
        {
            QueryString = HttpContext.Request.QueryString.HasValue ? HttpContext.Request.QueryString.Value!.TrimStart('?') : "";

            return Task.CompletedTask;
        }

        public async Task<IActionResult> OnPostAsync(CancellationToken ct)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    throw new Exception("유효성 검사에 실패하였습니다.");
                }

                var command = new CreateDocument.Command(
                    Input.Code,
                    Input.Subject,
                    Input.Content,
                    Input.IsActive
                );

                await mediator.Send(command, ct);

                TempData["SuccessMessage"] = $"{Input.Subject} 문서가 등록되었습니다.";

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

                return Redirect($"/Document/Write?{QueryString}");
            }
        }
    }
}