import 'package:dio/dio.dart';
import '../../../../core/config/api_endpoints.dart';
import '../models/approval_model.dart';

/// Remote datasource for approval operations.
class ApprovalsDatasource {
  final Dio _dio;

  ApprovalsDatasource(this._dio);

  /// Fetches all approvals, optionally filtered by status.
  Future<List<ApprovalModel>> fetchAll({String? status}) async {
    final queryParams = <String, dynamic>{};
    if (status != null) queryParams['status'] = status;

    final response = await _dio.get(
      ApiEndpoints.approvals,
      queryParameters: queryParams.isNotEmpty ? queryParams : null,
    );

    final data = response.data;
    List<dynamic> items;

    if (data is List) {
      items = data;
    } else if (data is Map && data.containsKey('items')) {
      items = data['items'] as List;
    } else {
      items = [];
    }

    return items
        .map((item) => ApprovalModel.fromJson(item as Map<String, dynamic>))
        .toList();
  }

  /// Approves a command by approval ID.
  Future<ApprovalModel> approve(String id) async {
    final response =
        await _dio.post('${ApiEndpoints.approvals}/$id/approve');
    return ApprovalModel.fromJson(response.data as Map<String, dynamic>);
  }

  /// Rejects a command by approval ID.
  Future<ApprovalModel> reject(String id) async {
    final response =
        await _dio.post('${ApiEndpoints.approvals}/$id/reject');
    return ApprovalModel.fromJson(response.data as Map<String, dynamic>);
  }
}
