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

namespace TaxBaik.Web.Pages.Admin.Blog;

[Authorize(AuthenticationSchemes = AdminAuthDefaults.Scheme)]
public class CreateModel(BlogService blogService, CategoryService categoryService) : PageModel
{
    [BindProperty]
    public CreateBlogPostDto Input { get; set; } = new()
    {
        Content = string.Empty,
        Title = string.Empty
    };

    public IReadOnlyList<Category> Categories { get; private set; } = [];

    public async Task<IActionResult> OnGetAsync(CancellationToken ct)
    {
        Categories = (await EnsureCategoriesAsync(ct)).ToList();
        if (Categories.Count > 0)
            Input.CategoryId = Categories[0].Id;

        return Page();
    }

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

        await blogService.CreateAsync(Input, ct);
        return RedirectToPage("/Admin/Blog/Index");
    }

    private async Task<IEnumerable<Category>> EnsureCategoriesAsync(CancellationToken ct)
    {
        var categories = (await categoryService.GetAllAsync(ct)).ToList();
        if (categories.Count > 0)
            return categories;

        var defaults = new[]
        {
            ("사업자 세무", "business-tax", 1),
            ("부동산 세금", "real-estate-tax", 2),
            ("종합소득세", "income-tax", 3),
            ("부가가치세", "vat", 4),
            ("가족자산·증여", "family-asset", 5)
        };

        foreach (var (name, slug, sortOrder) in defaults)
        {
            await categoryService.CreateAsync(name, null, ct);
        }

        return await categoryService.GetAllAsync(ct);
    }
}
