using Application.Abstractions.Messaging.Email;
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.Config.Test
{
    public class EmailModel(IMediator mediator, IOptions<AppSettings> options, IMailService mailService) : PageModel
    {
        public readonly AppSettings Settings = options.Value;

        [BindProperty]
        [MaxLength(256)]
        [DataType(DataType.EmailAddress)]
        [DisplayName("To Address")]
        public string? ToAddress { get; set; }

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

        public async Task OnGetAsync(CancellationToken ct)
        {
            var config = await mediator.Send(new GetConfig.Query(), ct);
            if (config is not null)
            {
                Input = InputModel.From(config);
            }
        }

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

            await mailService.SendAsync(
                new SendData(
                    ToAddress: ToAddress!,
                    Subject: $"[TEST] SMTP 이메일 발송 테스트 - {DateTime.Now:yyyy-MM-dd HH:mm:ss}",
                    MessageHtml: $"""
                                 <h3>테스트 메일</h3>
                                 <ul>
                                     <li>From: {Settings.SMTP.FromName} &lt;{Settings.SMTP.FromEmail}&gt;</li>
                                     <li>To: {ToAddress}</li>
                                     <li>Host: {Settings.SMTP.Host}:{Settings.SMTP.Port}</li>
                                     <li>TLS: {Settings.SMTP.UseStartTls}</li>
                                 </ul>
                                 """,
                    MessageText: $"TEST MAIL\nFrom={Settings.SMTP.FromEmail}\nTo={ToAddress}\nHost={Settings.SMTP.Host}:{Settings.SMTP.Port}\nTLS={Settings.SMTP.UseStartTls}"
                ),
                ct
            );

            TempData["SuccessMessage"] = "테스트 이메일을 발송했습니다.";

            return RedirectToPage();
        }

        public sealed class InputModel
        {
            public UpdateConfig.Request.BasicConfigDto Basic { get; set; } = new();

            public static InputModel From(GetConfig.Response config)
            {
                var req = UpdateConfig.Request.From(config);

                return new()
                {
                    Basic = req.Basic
                };
            }
        }
    }
}