import 'dart:io';

import 'package:http/http.dart';
import 'package:http_parser/http_parser.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/profile/certificates/data/models/certificate_model.dart';
import 'package:krow/features/profile/certificates/data/models/staff_certificate.dart';

import 'certificates_gql.dart';

@injectable
class CertificatesApiProvider {
  final ApiClient _apiClient;

  CertificatesApiProvider(this._apiClient);

  Future<List<CertificateModel>> fetchCertificates() async {
    var result = await _apiClient.query(schema: getCertificatesQuery);

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

    return result.data!['certificates'].map<CertificateModel>((e) {
      return CertificateModel.fromJson(e);
    }).toList();
  }

  Future<PaginationWrapper<StaffCertificate>> fetchStaffCertificates() async {
    var result = await _apiClient.query(schema: getStaffCertificatesQuery);

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

    return PaginationWrapper.fromJson(result.data!['staff_certificates'],
        (json) => StaffCertificate.fromJson(json));
  }

  Future<StaffCertificate> putStaffCertificate(
      String certificateId, String imagePath, String certificateDate) async {
    var byteData = File(imagePath).readAsBytesSync();

    var multipartFile = MultipartFile.fromBytes(
      'file',
      byteData,
      filename: '${DateTime.now().millisecondsSinceEpoch}.jpg',
      contentType: MediaType('image', 'jpg'),
    );

    final Map<String, dynamic> variables = {
      'certificate_id': certificateId,
      'expiration_date': certificateDate,
      'file': multipartFile,
    };
    var result = await _apiClient.mutate(
        schema: putStaffCertificateMutation, body: {'input': variables});

    if (result.hasException) {
      throw Exception(result.exception.toString());
    } else {
      return StaffCertificate.fromJson(
          result.data!['upload_staff_certificate']);
    }
  }

  Future<void> deleteStaffCertificate(String certificateId) async {
    final Map<String, dynamic> variables = {
      'id': certificateId,
    };
    var result = await _apiClient.mutate(
        schema: deleteStaffCertificateMutation, body: variables);

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