import 'package:dio/dio.dart';

import '../../../../../core/network/api_client.dart';
import '../../../../../core/network/api_routes.dart';
import '../../domain/entities/approval_approver_candidate.dart';
import '../../domain/repositories/approval_approver_repository.dart';
import '../dtos/approval_approver_candidate_dto.dart';

/// 승인자 자동완성용 원격 저장소 구현체.
class ApprovalApproverRepositoryRemote implements ApprovalApproverRepository {
  ApprovalApproverRepositoryRemote({required ApiClient apiClient})
    : _api = apiClient;

  final ApiClient _api;

  static const _basePath = '${ApiRoutes.apiV1}/users';

  @override
  Future<List<ApprovalApproverCandidate>> search({
    required String keyword,
    int limit = 20,
  }) async {
    final trimmed = keyword.trim();
    if (trimmed.isEmpty) {
      return const [];
    }

    final response = await _api.get<Map<String, dynamic>>(
      _basePath,
      query: _buildQuery(limit: limit, keyword: trimmed),
      options: Options(responseType: ResponseType.json),
    );

    return _mapCandidates(response.data);
  }

  @override
  Future<ApprovalApproverCandidate?> fetchById(int id) async {
    final response = await _api.get<Map<String, dynamic>>(
      '$_basePath/$id',
      query: ApiClient.buildQuery(include: const ['group']),
      options: Options(responseType: ResponseType.json),
    );

    final payload = _api.unwrapAsMap(response);
    if (payload.isEmpty) {
      return null;
    }
    return ApprovalApproverCandidateDto.fromJson(payload).toEntity();
  }

  @override
  Future<List<ApprovalApproverCandidate>> listInitial({int limit = 20}) async {
    final response = await _api.get<Map<String, dynamic>>(
      _basePath,
      query: _buildQuery(limit: limit),
      options: Options(responseType: ResponseType.json),
    );

    return _mapCandidates(response.data);
  }

  Map<String, dynamic> _buildQuery({required int limit, String? keyword}) {
    return ApiClient.buildQuery(
      page: 1,
      pageSize: limit,
      q: keyword,
      sort: 'name',
      order: 'asc',
      include: const ['group'],
      filters: const {'is_active': true},
    );
  }

  List<ApprovalApproverCandidate> _mapCandidates(
    Map<String, dynamic>? payload,
  ) {
    return (payload?['items'] as List<dynamic>? ?? const [])
        .whereType<Map<String, dynamic>>()
        .map(ApprovalApproverCandidateDto.fromJson)
        .map((dto) => dto.toEntity())
        .toList(growable: false);
  }
}
