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

namespace TaxBaik.Web.Endpoints.Inquiry;

public class UpdateStatusEndpoint : Endpoint<UpdateStatusRequest, MessageResponse>
{
    private readonly InquiryService _inquiryService;

    public UpdateStatusEndpoint(InquiryService inquiryService)
    {
        _inquiryService = inquiryService;
    }

    public override void Configure()
    {
        Put("/api/inquiry/{id}/status");
        Policies("Bearer");
    }

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

        try
        {
            var changedBy = User.FindFirstValue(ClaimTypes.Name) ?? User.Identity?.Name;
            await _inquiryService.UpdateStatusAsync(id, request.Status, changedBy);
            await SendAsync(new MessageResponse { Message = "상태가 변경되었습니다." }, 200, cancellation: ct);
        }
        catch (ValidationException ex)
        {
            ThrowError(ex.Message);
        }
    }
}
