import 'package:dio/dio.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../models/colonia.dart';
import '../network/api_client.dart';

final coloniasServiceProvider = Provider<ColoniasService>((ref) {
  return ColoniasService(ref.read(apiClientProvider));
});

class ColoniasService {
  ColoniasService(this._apiClient);

  final Dio _apiClient;

  Future<List<Colonia>> getColonias() async {
    final response = await _apiClient.get<dynamic>('/colonias');
    final data = response.data;

    if (data == null) {
      return const <Colonia>[];
    }

    final rawList = switch (data) {
      List<dynamic> value => value,
      Map<String, dynamic> value when value['data'] is List<dynamic> =>
        value['data'] as List<dynamic>,
      Map<String, dynamic> value when value['colonias'] is List<dynamic> =>
        value['colonias'] as List<dynamic>,
      _ => const <dynamic>[],
    };

    return rawList
        .whereType<Map<String, dynamic>>()
        .map(Colonia.fromJson)
        .where((colonia) => colonia.id.isNotEmpty && colonia.nombre.isNotEmpty)
        .toList(growable: false);
  }
}
