import 'package:dio/dio.dart';
import 'package:injectable/injectable.dart';
import '../../domain/entities/type_reference_entity.dart';
import '../../domain/repositories/org_types_repository.dart';
import '../datasources/org_types_remote_datasource.dart';

@LazySingleton(as: IOrgTypesRepository)
class OrgTypesRepositoryImpl implements IOrgTypesRepository {
  final OrgTypesRemoteDataSource _dataSource;

  const OrgTypesRepositoryImpl(this._dataSource);

  @override
  Future<List<TypeReferenceEntity>> getOrgTypes() async {
    try {
      final models = await _dataSource.getOrgTypes();
      return models.map((m) => m.toEntity()).toList();
    } on DioException catch (e) {
      throw Exception('Erreur réseau: ${e.message}');
    }
  }

  @override
  Future<TypeReferenceEntity> createOrgType({
    required String code,
    required String libelle,
    String? description,
    String? couleur,
    int ordreAffichage = 0,
  }) async {
    try {
      final model = await _dataSource.createOrgType({
        'domaine': 'TYPE_ORGANISATION',
        'code': code.toUpperCase().replaceAll(' ', '_'),
        'libelle': libelle,
        if (description != null) 'description': description,
        if (couleur != null) 'couleur': couleur,
        'ordreAffichage': ordreAffichage,
        'estDefaut': false,
        'estSysteme': false,
        'actif': true,
      });
      return model.toEntity();
    } on DioException catch (e) {
      throw Exception('Erreur réseau: ${e.message}');
    }
  }

  @override
  Future<TypeReferenceEntity> updateOrgType({
    required String id,
    required String code,
    required String libelle,
    String? description,
    String? couleur,
    int ordreAffichage = 0,
  }) async {
    try {
      final model = await _dataSource.updateOrgType(id, {
        'domaine': 'TYPE_ORGANISATION',
        'code': code.toUpperCase().replaceAll(' ', '_'),
        'libelle': libelle,
        if (description != null) 'description': description,
        if (couleur != null) 'couleur': couleur,
        'ordreAffichage': ordreAffichage,
      });
      return model.toEntity();
    } on DioException catch (e) {
      throw Exception('Erreur réseau: ${e.message}');
    }
  }

  @override
  Future<void> deleteOrgType(String id) async {
    try {
      await _dataSource.deleteOrgType(id);
    } on DioException catch (e) {
      throw Exception('Erreur réseau: ${e.message}');
    }
  }
}
