import 'package:dio/dio.dart';
import 'package:injectable/injectable.dart';
import 'package:unionflow_mobile_apps/core/network/api_client.dart';
import '../models/type_reference_model.dart';

@injectable
class OrgTypesRemoteDataSource {
  final ApiClient _apiClient;
  static const _basePath = '/api/references/types-organisation';

  const OrgTypesRemoteDataSource(this._apiClient);

  Future<List<TypeReferenceModel>> getOrgTypes() async {
    final response = await _apiClient.get(_basePath);
    if (response.statusCode == 200) {
      final dynamic raw = response.data;
      final List<dynamic> data = raw is List<dynamic>
          ? raw
          : ((raw as Map<String, dynamic>)['data'] as List<dynamic>? ?? []);
      return data
          .map((e) => TypeReferenceModel.fromJson(e as Map<String, dynamic>))
          .toList();
    }
    throw DioException(
      requestOptions: response.requestOptions,
      response: response,
      message: 'Erreur lors de la récupération des types: ${response.statusCode}',
    );
  }

  Future<TypeReferenceModel> createOrgType(Map<String, dynamic> body) async {
    final response = await _apiClient.post(_basePath, data: body);
    if (response.statusCode == 200 || response.statusCode == 201) {
      return TypeReferenceModel.fromJson(response.data as Map<String, dynamic>);
    }
    throw DioException(
      requestOptions: response.requestOptions,
      response: response,
      message: 'Erreur lors de la création du type: ${response.statusCode}',
    );
  }

  Future<TypeReferenceModel> updateOrgType(String id, Map<String, dynamic> body) async {
    final response = await _apiClient.put('$_basePath/$id', data: body);
    if (response.statusCode == 200) {
      return TypeReferenceModel.fromJson(response.data as Map<String, dynamic>);
    }
    throw DioException(
      requestOptions: response.requestOptions,
      response: response,
      message: 'Erreur lors de la mise à jour du type: ${response.statusCode}',
    );
  }

  Future<void> deleteOrgType(String id) async {
    final response = await _apiClient.delete('$_basePath/$id');
    if (response.statusCode != 200 && response.statusCode != 204) {
      throw DioException(
        requestOptions: response.requestOptions,
        response: response,
        message: 'Erreur lors de la suppression du type: ${response.statusCode}',
      );
    }
  }
}
