using FastEndpoints;
using TaxBaik.Application.DTOs;
using TaxBaik.Application.Services;

namespace TaxBaik.Web.Endpoints.Client;

public class CreateEndpoint : Endpoint<CreateClientDto, object>
{
    private readonly ClientService _clientService;

    public CreateEndpoint(ClientService clientService)
    {
        _clientService = clientService;
    }

    public override void Configure()
    {
        Post("/api/client");
        Policies("Bearer");
    }

    public override async Task HandleAsync(CreateClientDto request, CancellationToken ct)
    {
        try
        {
            var clientId = await _clientService.CreateAsync(request);
            var client = await _clientService.GetByIdAsync(clientId);
            await SendAsync(client!, 201, cancellation: ct);
        }
        catch (ValidationException ex)
        {
            ThrowError(ex.Message);
        }
    }
}
