using System.Security.Claims;
using FastEndpoints;
using TaxBaik.Application.Services;

namespace TaxBaik.Web.Endpoints.Inquiry;

public class ConvertToClientEndpoint : Endpoint<ConvertToClientRequest, ConvertToClientResponse>
{
    private readonly InquiryService _inquiryService;
    private readonly ClientService _clientService;

    public ConvertToClientEndpoint(InquiryService inquiryService, ClientService clientService)
    {
        _inquiryService = inquiryService;
        _clientService = clientService;
    }

    public override void Configure()
    {
        Post("/api/inquiry/{id}/convert-to-client");
        Policies("Bearer");
    }

    public override async Task HandleAsync(ConvertToClientRequest request, CancellationToken ct)
    {
        var id = Route<int>("id");
        var inquiry = await _inquiryService.GetByIdAsync(id);
        if (inquiry == null)
        {
            ThrowError("문의를 찾을 수 없습니다.", statusCode: 404);
        }

        if (inquiry.ClientId != null)
        {
            ThrowError("이미 고객 카드가 연결되어 있습니다.", statusCode: 400);
        }

        try
        {
            var clientId = await _clientService.CreateFromInquiryAsync(
                request.Name ?? inquiry.Name,
                request.Phone ?? inquiry.Phone,
                request.ServiceType ?? inquiry.ServiceType);

            await _inquiryService.LinkClientAsync(inquiry.Id, clientId);
            await _inquiryService.UpdateStatusAsync(inquiry.Id, "consulting", User.FindFirstValue(ClaimTypes.Name) ?? "system");

            await SendAsync(new ConvertToClientResponse
            {
                ClientId = clientId,
                Message = "고객 카드가 생성되었습니다."
            }, 200, cancellation: ct);
        }
        catch (Exception ex)
        {
            ThrowError(ex.Message);
        }
    }
}
