import 'package:dio/dio.dart';
import 'package:superport_v2/core/common/models/paginated_result.dart';
import 'package:superport_v2/core/network/api_client.dart';
import 'package:superport_v2/core/network/api_routes.dart';

import '../../domain/entities/approval_history_record.dart';
import '../../domain/repositories/approval_history_repository.dart';
import '../dtos/approval_history_record_dto.dart';

/// 결재 이력 API를 호출하는 원격 저장소 구현체.
class ApprovalHistoryRepositoryRemote implements ApprovalHistoryRepository {
  ApprovalHistoryRepositoryRemote({required ApiClient apiClient})
    : _api = apiClient;

  final ApiClient _api;

  static const _basePath = '${ApiRoutes.apiV1}/approval-histories';
  static const _defaultInclude = <String>[
    'approval',
    'step',
    'approval_action',
    'approver',
    'from_status',
    'to_status',
  ];

  /// 결재 이력 목록을 조회한다.
  @override
  Future<PaginatedResult<ApprovalHistoryRecord>> list({
    int page = 1,
    int pageSize = 20,
    String? query,
    int? approvalActionId,
    DateTime? from,
    DateTime? to,
  }) async {
    final resolvedQuery = ApiClient.buildQuery(
      page: page,
      pageSize: pageSize,
      q: query,
      include: _defaultInclude,
      filters: {
        if (from != null) 'action_from': from,
        if (to != null) 'action_to': to,
        if (approvalActionId != null) 'approval_action_id': approvalActionId,
      },
    );
    final response = await _api.get<Map<String, dynamic>>(
      _basePath,
      query: resolvedQuery.isEmpty ? null : resolvedQuery,
      options: Options(responseType: ResponseType.json),
    );

    return ApprovalHistoryRecordDto.parsePaginated(response.data);
  }
}
