using SharedKernel;
using Application.Abstractions.Messaging;
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}");
            }
        }
    }
}