OnProfNext/OnProfNext.Client/Services/BookingApiService.cs
2025-10-17 10:41:53 +02:00

104 lines
4.2 KiB
C#

using OnProfNext.Shared.Models.DTOs;
using System.Net.Http.Json;
using System.Text.Json;
namespace OnProfNext.Client.Services
{
public class BookingApiService
{
private readonly HttpClient _httpClient;
public BookingApiService(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task<(bool Success, List<BookingDto>? Data, string? Error)> GetMyBookingsAsync()
{
try
{
var bookings = await _httpClient.GetFromJsonAsync<List<BookingDto>>("api/bookings/mine");
Console.WriteLine($"Received bookings: {JsonSerializer.Serialize(bookings, new JsonSerializerOptions { WriteIndented = true })}");
return (true, bookings ?? new(), null);
}
catch (Exception ex)
{
return (false, null, $"Fehler beim Laden der Buchungen: {ex.Message}");
}
}
public async Task<(bool Success, List<BookingDto>? Data, string? Error)> GetBookingsByOrderAsync(int orderId)
{
try
{
var bookings = await _httpClient.GetFromJsonAsync<List<BookingDto>>($"api/bookings/byorder/{orderId}");
Console.WriteLine($"Received bookings for order {orderId}: {JsonSerializer.Serialize(bookings, new JsonSerializerOptions { WriteIndented = true })}");
return (true, bookings ?? new(), null);
}
catch (Exception ex)
{
return (false, null, $"Fehler beim Laden der Buchungen: {ex.Message}");
}
}
public async Task<(bool Success, string? Error)> CreateBookingAsync(BookingCreateDto dto)
{
try
{
// Explizite Serialisierung für Debugging
var jsonPayload = JsonSerializer.Serialize(new
{
dto.OrderId,
date = dto.Date.ToString("yyyy-MM-ddTHH:mm:ss"),
dto.Hours,
dto.MandantId,
dto.Description
}, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
Console.WriteLine($"Sending booking to API: {jsonPayload}");
var content = new StringContent(jsonPayload, System.Text.Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync("api/bookings", content);
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Booking API call successful.");
return (true, null);
}
else
{
var errorContent = await response.Content.ReadAsStringAsync();
Console.WriteLine($"API error response: {errorContent}");
return (false, $"Fehler beim Speichern: {response.ReasonPhrase}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Exception in CreateBookingAsync: {ex.Message}");
return (false, ex.Message);
}
}
public async Task<(bool Success, string? Error)> DeleteBookingAsync(int id)
{
try
{
var response = await _httpClient.DeleteAsync($"api/bookings/{id}");
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Delete booking API call successful.");
return (true, null);
}
else
{
var errorContent = await response.Content.ReadAsStringAsync();
Console.WriteLine($"API error response: {errorContent}");
return (false, $"Fehler beim Löschen: {response.ReasonPhrase}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Exception in DeleteBookingAsync: {ex.Message}");
return (false, ex.Message);
}
}
}
}