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.Announcements;

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

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

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

        Input = new AnnouncementDto
        {
            Id = item.Id,
            Title = item.Title,
            Content = item.Content,
            DisplayType = item.DisplayType,
            IsActive = item.IsActive,
            StartsAt = item.StartsAt,
            EndsAt = item.EndsAt,
            SortOrder = item.SortOrder
        };

        return Page();
    }

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

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

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