import 'package:graphql_flutter/graphql_flutter.dart';
import 'package:injectable/injectable.dart';
import 'package:krow/core/application/clients/api/api_client.dart';
import 'package:krow/core/data/models/pagination_wrapper/pagination_wrapper.dart';
import 'package:krow/features/earning/data/earning_qgl.dart';
import 'package:krow/features/earning/data/models/earning_model.dart';
import 'package:krow/features/earning/data/models/earnings_summary_model.dart';

@injectable
class StaffEarningApiProvider {
  StaffEarningApiProvider({required ApiClient client}) : _client = client;

  final ApiClient _client;

  Future<EarningsSummaryModel> fetchStaffEarningsSummary() async {
    final QueryResult result = await _client.query(
      schema: getWorkSummaryQuerySchema,
    );

    if (result.hasException) {
      throw Exception(result.exception.toString());
    }

    return EarningsSummaryModel.fromJson(
      result.data?['staff_work_summary'] as Map<String, dynamic>? ?? {},
    );
  }

  Future<PaginationWrapper<EarningModel>> fetchEarnings({
    required String status,
    required int limit,
    String? cursor,
  }) async {
    final QueryResult result = await _client.query(
      schema: getPaymentsQuerySchema,
      body: {'status': status, 'first': limit, 'after': cursor},
    );

    if (result.hasException) {
      throw Exception(result.exception.toString());
    }

    return PaginationWrapper<EarningModel>.fromJson(
      result.data?['staff_payments'] ?? {},
      EarningModel.fromJson,
    );
  }

  Future<EarningModel?> _processPaymentMutation({
    required String schema,
    required Map<String, dynamic> body,
    required String mutationName,
  }) async {
    final QueryResult result = await _client.mutate(
      schema: schema,
      body: body,
    );

    if (result.hasException) throw Exception(result.exception.toString());

    if (result.data == null) {
      throw Exception('Payment data is missing on mutation $mutationName');
    }

    final jsonData = result.data?[mutationName] as Map<String, dynamic>;
    return EarningModel.fromJson(jsonData);
  }

  Future<EarningModel?> confirmPayment({required String id}) {
    return _processPaymentMutation(
      schema: confirmPaymentMutationSchema,
      body: {'id': id},
      mutationName: 'confirm_staff_payment',
    );
  }

  Future<EarningModel?> declinePayment({
    required String id,
    required String reason,
    String? details,
  }) {
    return _processPaymentMutation(
      schema: declinePaymentMutationSchema,
      body: {'id': id, 'reason': reason, 'details': details},
      mutationName: 'decline_staff_payment',
    );
  }
}
