import 'package:injectable/injectable.dart';
import 'package:krow/core/application/clients/api/api_client.dart';
import 'package:krow/core/application/clients/api/gql.dart';
import 'package:krow/core/data/models/skill.dart';
import 'package:krow/core/data/models/staff_role.dart';
import 'package:krow/features/profile/role/data/gql.dart';

@injectable
class StaffRoleApiProvider {
  final ApiClient _apiClient;

  StaffRoleApiProvider(this._apiClient);

  Future<List<StaffRole>> fetchStaffRoles() async {
    var result = await _apiClient.query(schema: getStaffRolesQuery);

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

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

  Future<List<Skill>> fetchSkills() {
    return _apiClient.query(schema: getSkillsQuery).then((result) {
      if (result.hasException) {
        throw Exception(result.exception.toString());
      }

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

  Future<String> saveStaffRole(StaffRole role) {
    return _apiClient.mutate(schema: attachStaffRolesMutation, body: {
      'roles': [
        {
          'level': role.level.toString().split('.').last,
          'experience': role.experience,
          'skill_id': role.skill!.id,
        }
      ],
    }).then((result) {
      if (result.hasException) {
        throw Exception(result.exception.toString());
      }

      return '';
    });
  }

  Future<void> deleteStaffRole(StaffRole role) {
    return _apiClient.mutate(schema: detachStaffRolesMutation, body: {
      'ids': [role.skill?.id],
    }).then((result) {
      if (result.hasException) {
        throw Exception(result.exception.toString());
      }
    });
  }
}
