import 'package:dio/dio.dart';

import '../../../../../core/network/api_client.dart';
import '../../../../../core/network/api_routes.dart';
import '../../domain/entities/lookup_item.dart';
import '../../domain/repositories/inventory_lookup_repository.dart';
import '../dtos/lookup_item_dto.dart';

/// 인벤토리 공통 룩업 API 호출 구현체.
class InventoryLookupRepositoryRemote implements InventoryLookupRepository {
  InventoryLookupRepositoryRemote({required ApiClient apiClient})
    : _api = apiClient;

  final ApiClient _api;

  static const _transactionTypesPath = '${ApiRoutes.apiV1}/transaction-types';
  static const _transactionStatusesPath =
      '${ApiRoutes.apiV1}/transaction-statuses';
  static const _approvalStatusesPath = '${ApiRoutes.apiV1}/approval-statuses';
  static const _approvalActionsPath = '${ApiRoutes.apiV1}/approval-actions';

  @override
  Future<List<LookupItem>> fetchTransactionTypes({bool activeOnly = true}) {
    return _fetchList(_transactionTypesPath, activeOnly: activeOnly);
  }

  @override
  Future<List<LookupItem>> fetchTransactionStatuses({bool activeOnly = true}) {
    return _fetchList(_transactionStatusesPath, activeOnly: activeOnly);
  }

  @override
  Future<List<LookupItem>> fetchApprovalStatuses({bool activeOnly = true}) {
    return _fetchList(_approvalStatusesPath, activeOnly: activeOnly);
  }

  @override
  Future<List<LookupItem>> fetchApprovalActions({bool activeOnly = true}) {
    return _fetchList(
      _approvalActionsPath,
      activeOnly: activeOnly,
      // Approval actions는 active 필터가 없을 수 있어 조건적으로 전달한다.
      includeActiveFilter: false,
    );
  }

  Future<List<LookupItem>> _fetchList(
    String path, {
    required bool activeOnly,
    bool includeActiveFilter = true,
  }) async {
    final response = await _api.get<Map<String, dynamic>>(
      path,
      query: {
        'page': 1,
        'page_size': 200,
        if (includeActiveFilter && activeOnly) 'active': true,
      },
      options: Options(responseType: ResponseType.json),
    );
    return LookupItemDto.parseList(response.data ?? const {});
  }
}
