import '../models/marketplace.dart';
import 'api_client.dart';

class MarketplaceService {
  final _client = ApiClient.instance;

  // After envelope unwrap: [ "City1", "City2", ... ]
  Future<List<String>> getCities() async {
    final res = await _client.get('/marketplace/cities');
    final data = res.data;
    if (data is List) {
      return data.whereType<String>().toList();
    }
    return [];
  }

  // After envelope unwrap: [ { id, title, ... }, ... ]
  Future<List<MarketplaceOffer>> getOffers() async {
    final res = await _client.get('/marketplace/offers');
    final data = res.data;
    if (data is List) {
      return data
          .map((e) => MarketplaceOffer.fromJson(e as Map<String, dynamic>))
          .toList();
    }
    return [];
  }

  // After envelope unwrap: [ { id, make, model, ... }, ... ]
  Future<MarketplaceSearchResult> search({
    String? city,
    DateTime? startDate,
    DateTime? endDate,
    String? category,
    String? transmission,
    String? make,
    int? maxPriceCents,
    int page = 1,
    int pageSize = 20,
  }) async {
    final res = await _client.get('/marketplace/search', params: {
      'page': page,
      'pageSize': pageSize,
      if (city != null && city.isNotEmpty) 'city': city,
      if (startDate != null)
        'startDate': '${startDate.toIso8601String().substring(0, 10)}T00:00:00.000Z',
      if (endDate != null)
        'endDate': '${endDate.toIso8601String().substring(0, 10)}T00:00:00.000Z',
      'category': ?category,
      'transmission': ?transmission,
      if (make != null && make.isNotEmpty) 'make': make,
      'maxPrice': ?maxPriceCents,
    });

    final data = res.data;
    if (data is List) {
      final vehicles = data
          .map((e) => MarketplaceVehicle.fromJson(e as Map<String, dynamic>))
          .toList();
      return MarketplaceSearchResult(
        data: vehicles,
        total: vehicles.length,
        page: page,
        pageSize: pageSize,
      );
    }
    // Fallback: paginated object shape { data: [...], total: N }
    return MarketplaceSearchResult.fromJson(data as Map<String, dynamic>);
  }

  Future<String> createReservation({
    required String vehicleId,
    required String companySlug,
    required String firstName,
    required String lastName,
    required String email,
    required String phone,
    required String driverLicense,
    required DateTime startDate,
    required DateTime endDate,
    String? notes,
    String language = 'en',
  }) async {
    final res = await _client.post('/marketplace/reservations', data: {
      'vehicleId': vehicleId,
      'companySlug': companySlug,
      'firstName': firstName,
      'lastName': lastName,
      'email': email,
      'phone': phone,
      'driverLicense': driverLicense,
      'startDate': '${startDate.toIso8601String().substring(0, 10)}T00:00:00.000Z',
      'endDate': '${endDate.toIso8601String().substring(0, 10)}T00:00:00.000Z',
      if (notes != null && notes.isNotEmpty) 'notes': notes,
      'language': language,
    });
    final data = res.data as Map<String, dynamic>;
    return data['reservationId'] as String;
  }
}
