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

namespace Admin.Pages.Member.List;

public class ApproveModel(IMediator mediator) : PageModel
{
    [BindProperty]
    public string? QueryString { get; set; }

    public string? ReceiveSMSConsentAt { get; set; }
    public string? ReceiveEmailConsentAt { get; set; }
    public string? ReceiveNoteConsentAt { get; set; }
    public string? DisclosureInvestConsentAt { get; set; }

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

    public sealed class InputModel
    {
        public int MemberID { get; set; }

        [DisplayName("SMS 수신")]
        public bool IsReceiveSMS { get; set; }

        [DisplayName("이메일 수신")]
        public bool IsReceiveEmail { get; set; }

        [DisplayName("쪽지 수신")]
        public bool IsReceiveNote { get; set; }

        [DisplayName("투자 현황 공개")]
        public bool IsDisclosureInvest { get; set; }
    }

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

        ReceiveSMSConsentAt = result.ReceiveSMSConsentAt.GetDateAt();
        ReceiveEmailConsentAt = result.ReceiveEmailConsentAt.GetDateAt();
        ReceiveNoteConsentAt = result.ReceiveNoteConsentAt.GetDateAt();
        DisclosureInvestConsentAt = result.DisclosureInvestConsentAt.GetDateAt();

        Input = new InputModel
        {
            MemberID = result.MemberID,
            IsReceiveSMS = result.IsReceiveSMS,
            IsReceiveEmail = result.IsReceiveEmail,
            IsReceiveNote = result.IsReceiveNote,
            IsDisclosureInvest = result.IsDisclosureInvest
        };

        QueryString = Request.QueryString.ToString();
    }

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

            await mediator.Send(new ApproveMember.Command(
                Input.MemberID,
                Input.IsReceiveSMS,
                Input.IsReceiveEmail,
                Input.IsReceiveNote,
                Input.IsDisclosureInvest
            ), ct);

            TempData["SuccessMessage"] = "알림 및 동의 정보가 수정되었습니다.";
        }
        catch (Exception e)
        {
            TempData["ErrorMessages"] = e.Message;
        }

        return Redirect($"/Member/List/Approve/{Input.MemberID}{QueryString}");
    }
}