import 'package:dio/dio.dart';
import 'package:syncrow_web/pages/space_management_v2/modules/tags/domain/models/tag.dart';
import 'package:syncrow_web/pages/space_management_v2/modules/tags/domain/params/load_tags_param.dart';
import 'package:syncrow_web/pages/space_management_v2/modules/tags/domain/services/tags_service.dart';
import 'package:syncrow_web/services/api/api_exception.dart';
import 'package:syncrow_web/services/api/http_service.dart';
import 'package:syncrow_web/utils/constants/api_const.dart';

final class RemoteTagsService implements TagsService {
  const RemoteTagsService(this._httpService);

  final HTTPService _httpService;

  static const _defaultErrorMessage = 'Failed to load tags';

  @override
  Future<List<Tag>> loadTags(LoadTagsParam param) async {
    if (param.projectUuid == null) {
      throw Exception('Project UUID is required');
    }

    try {
      final response = await _httpService.get(
        path: ApiEndpoints.listTags.replaceAll(
          '{projectUuid}',
          param.projectUuid!,
        ),
        expectedResponseModel: (json) {
          final result = json as Map<String, dynamic>;
          final data = result['data'] as List<dynamic>;
          return data.map((e) => Tag.fromJson(e as Map<String, dynamic>)).toList();
        },
      );
      return response;
    } on DioException catch (e) {
      final message = e.response?.data as Map<String, dynamic>?;
      final error = message?['error'] as Map<String, dynamic>?;
      final errorMessage = error?['error'] as String? ?? '';
      final formattedErrorMessage = [
        _defaultErrorMessage,
        errorMessage,
      ].join(': ');
      throw APIException(formattedErrorMessage);
    } catch (e) {
      final formattedErrorMessage = [_defaultErrorMessage, '$e'].join(': ');
      throw APIException(formattedErrorMessage);
    }
  }
}
