import 'package:pshared/api/requests/ledger/create.dart';
import 'package:pshared/api/responses/ledger/accounts.dart';
import 'package:pshared/api/responses/ledger/balance.dart';
import 'package:pshared/data/mapper/describable.dart';
import 'package:pshared/data/mapper/ledger/account.dart';
import 'package:pshared/data/mapper/ledger/balance.dart';
import 'package:pshared/data/mapper/ledger/role.dart';
import 'package:pshared/data/mapper/ledger/type.dart';
import 'package:pshared/models/currency.dart';
import 'package:pshared/models/describable.dart';
import 'package:pshared/models/ledger/account.dart';
import 'package:pshared/models/ledger/balance.dart';
import 'package:pshared/models/ledger/role.dart';
import 'package:pshared/models/ledger/type.dart';
import 'package:pshared/service/authorization/service.dart';
import 'package:pshared/service/services.dart';
import 'package:pshared/utils/currency.dart';


class LedgerService {
  static const String _objectType = Services.ledger;

  Future<List<LedgerAccount>> list(String organizationRef) async {
    final json = await AuthorizationService.getGETResponse(
      _objectType,
      '/$organizationRef',
    );
    return LedgerAccountsResponse.fromJson(json).accounts.map((la) => la.toDomain()).toList();
  }

  Future<LedgerBalance> getBalance({
    required String organizationRef,
    required String ledgerAccountRef,
  }) async {
    final json = await AuthorizationService.getGETResponse(
      _objectType,
      '/$organizationRef/$ledgerAccountRef/balance',
    );
    return LedgerBalanceResponse.fromJson(json).balance.toDomain();
  }

  Future<void> create({
    required String organizationRef,
    required Describable describable,
    required String? ownerRef,
    required CurrencyCode currency,
  }) async => AuthorizationService.getPOSTResponse(
    _objectType,
    '/$organizationRef',
    CreateLedgerAccountRequest(
      describable: describable.toDTO(),
      ownerRef: ownerRef,
      allowNegative: false,
      role: LedgerAccountRole.operating.toDTO(),
      accountType: LedgerAccountType.asset.toDTO(),
      currency: currencyCodeToString(currency),
    ).toJson(),
  );
}
