// EN: HTTP client for Booking Service.
// VI: HTTP client cho Booking Service.

namespace OrderService.API.Infrastructure.HttpClients;

/// <summary>
/// EN: Client for calling Booking Service for appointment operations.
/// VI: Client gọi Booking Service để thực hiện thao tác đặt lịch.
/// </summary>
public class BookingServiceClient
{
    private readonly HttpClient _httpClient;
    private readonly ILogger<BookingServiceClient> _logger;

    public BookingServiceClient(
        HttpClient httpClient,
        ILogger<BookingServiceClient> logger)
    {
        _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    /// <summary>
    /// EN: Check availability for service appointment.
    /// VI: Kiểm tra lịch trống cho dịch vụ.
    /// </summary>
    public async Task<bool> CheckAvailabilityAsync(
        Guid serviceId,
        Guid shopId,
        DateTime startTime,
        int durationMinutes,
        CancellationToken cancellationToken = default)
    {
        try
        {
            _logger.LogInformation(
                "EN: Checking availability / VI: Kiểm tra lịch trống: Service={ServiceId}, Time={StartTime}",
                serviceId, startTime);

            var response = await _httpClient.GetAsync(
                $"/api/v1/bookings/check-availability?serviceId={serviceId}&shopId={shopId}&startTime={startTime:O}&duration={durationMinutes}",
                cancellationToken);

            if (!response.IsSuccessStatusCode)
            {
                return false;
            }

            var result = await response.Content.ReadFromJsonAsync<AvailabilityCheckResult>(cancellationToken);
            return result?.IsAvailable ?? false;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "EN: Error checking availability / VI: Lỗi khi kiểm tra lịch");
            return false;
        }
    }

    /// <summary>
    /// EN: Create appointment reservation.
    /// VI: Tạo đặt lịch.
    /// </summary>
    public async Task<Guid?> CreateAppointmentAsync(
        Guid serviceId,
        Guid shopId,
        Guid? customerId,
        DateTime startTime,
        int durationMinutes,
        CancellationToken cancellationToken = default)
    {
        try
        {
            _logger.LogInformation(
                "EN: Creating appointment / VI: Tạo đặt lịch: Service={ServiceId}, Time={StartTime}",
                serviceId, startTime);

            var request = new CreateAppointmentRequest(
                serviceId,
                shopId,
                customerId,
                startTime,
                durationMinutes);

            var response = await _httpClient.PostAsJsonAsync(
                "/api/v1/bookings/appointments",
                request,
                cancellationToken);

            if (!response.IsSuccessStatusCode)
            {
                return null;
            }

            var result = await response.Content.ReadFromJsonAsync<CreateAppointmentResult>(cancellationToken);
            return result?.AppointmentId;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "EN: Error creating appointment / VI: Lỗi khi tạo đặt lịch");
            return null;
        }
    }
}

public record AvailabilityCheckResult(bool IsAvailable);
public record CreateAppointmentRequest(
    Guid ServiceId,
    Guid ShopId,
    Guid? CustomerId,
    DateTime StartTime,
    int DurationMinutes);
public record CreateAppointmentResult(Guid AppointmentId);
