import 'package:logging/logging.dart';

import 'package:pshared/api/errors/unauthorized.dart';
import 'package:pshared/api/responses/employees.dart';
import 'package:pshared/models/organization/employee.dart';
import 'package:pshared/data/mapper/account/account.dart';
import 'package:pshared/service/authorization/service.dart';
import 'package:pshared/service/services.dart';


class EmployeesService {
  static final _logger = Logger('service.employees');
  static const String _objectType = Services.account;

  static Future<List<Employee>> list(String organizationRef) async {
    _logger.fine('Loading organization employees');
    return _getEmployees(AuthorizationService.getGETResponse(_objectType, '/list/$organizationRef'));
  }


  static Future<List<Employee>> _getEmployees(Future<Map<String, dynamic>> future) async {
    try {
      final responseJson = await future;
      final response = EmployeesResponse.fromJson(responseJson);
      final accounts = response.accounts.map((dto) => dto.toDomain()).toList();

      if (accounts.isEmpty) throw ErrorUnauthorized();
      _logger.fine('Fetched ${accounts.length} account(s)');
      return accounts;
    } catch (e, stackTrace) {
      _logger.severe('Failed to fetch accounts', e, stackTrace);
      rethrow;
    }
  }
}
