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

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

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

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

        Input = new CreateClientDto
        {
            Name = client.Name,
            CompanyName = client.CompanyName,
            Phone = client.Phone,
            Email = client.Email,
            ServiceType = client.ServiceType,
            TaxType = client.TaxType,
            Status = client.Status,
            Source = client.Source,
            Memo = client.Memo
        };

        return Page();
    }

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

        await clientService.UpdateAsync(Id, Input, ct);
        return RedirectToPage("/Admin/Clients/Detail", new { id = Id });
    }

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