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

namespace TaxBaik.Web.Pages.Admin.Faqs;

[Authorize(AuthenticationSchemes = AdminAuthDefaults.Scheme)]
public class EditModel(FaqService faqService) : PageModel
{
    [BindProperty(SupportsGet = true)]
    public int Id { get; set; }

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

    public IReadOnlyList<string> Categories => FaqService.Categories;

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

        Input = new Faq
        {
            Id = faq.Id,
            Question = faq.Question,
            Answer = faq.Answer,
            Category = faq.Category,
            SortOrder = faq.SortOrder,
            IsActive = faq.IsActive
        };

        return Page();
    }

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

        await faqService.UpdateAsync(Input, ct);
        return RedirectToPage("/Admin/Faqs/Index");
    }

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