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 EditModel(InquiryService inquiryService) : PageModel
{
    [BindProperty(SupportsGet = true)]
    public int Id { get; set; }

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

    public async Task<IActionResult> OnGetAsync(CancellationToken ct)
    {
        var inquiry = await inquiryService.GetByIdAsync(Id, ct);
        if (inquiry is null)
            return NotFound();

        Input = new UpdateInquiryDto
        {
            Name = inquiry.Name,
            Phone = inquiry.Phone,
            Email = inquiry.Email,
            ServiceType = inquiry.ServiceType,
            Message = inquiry.Message,
            Status = inquiry.Status,
            AdminMemo = inquiry.AdminMemo
        };

        return Page();
    }

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

        var updated = await inquiryService.UpdateAsync(Id, Input, ct);
        if (updated is null)
            return NotFound();

        return RedirectToPage("/Admin/Inquiries/Detail", new { id = Id });
    }

    public async Task<IActionResult> OnPostDeleteAsync(CancellationToken ct)
    {
        await inquiryService.DeleteAsync(Id, ct);
        return RedirectToPage("/Admin/Inquiries/Index");
    }
}
