using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using TaxBaik.Application.DTOs;
using TaxBaik.Application.Services;
using TaxBaik.Web.Services;

namespace TaxBaik.Web.Pages.Admin.Inquiries;

[Authorize(AuthenticationSchemes = AdminAuthDefaults.Scheme)]
public class CreateModel(InquiryService inquiryService) : PageModel
{
    [BindProperty]
    public UpdateInquiryDto Input { get; set; } = new();

    public IActionResult OnGet()
    {
        Input.Status = "new";
        return Page();
    }

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

        var inquiryId = await inquiryService.SubmitAsync(
            Input.Name,
            Input.Phone,
            string.IsNullOrWhiteSpace(Input.ServiceType) ? "기타" : Input.ServiceType,
            Input.Message,
            Input.Email,
            suppressNotification: true,
            ct: ct);

        if (!string.IsNullOrWhiteSpace(Input.Status))
            await inquiryService.UpdateStatusAsync(inquiryId, Input.Status, changedBy: User.Identity?.Name, ct: ct);

        if (!string.IsNullOrWhiteSpace(Input.AdminMemo))
            await inquiryService.UpdateAdminMemoAsync(inquiryId, Input.AdminMemo, ct);

        return RedirectToPage("/Admin/Inquiries/Index");
    }
}
