import 'package:pshared/data/dto/ledger/account.dart';
import 'package:pshared/data/mapper/describable.dart';
import 'package:pshared/data/mapper/ledger/balance.dart';
import 'package:pshared/data/mapper/ledger/role.dart';
import 'package:pshared/data/mapper/ledger/status.dart';
import 'package:pshared/data/mapper/ledger/type.dart';
import 'package:pshared/models/describable.dart';
import 'package:pshared/models/ledger/account.dart';


extension LedgerAccountDTOMapper on LedgerAccountDTO {
  LedgerAccount toDomain() {
    final mappedDescribable = describable?.toDomain();
    final fallbackName = metadata?['name']?.trim() ?? '';
    final name = mappedDescribable?.name.trim().isNotEmpty == true
        ? mappedDescribable!.name
        : fallbackName;

    return LedgerAccount(
      ledgerAccountRef: ledgerAccountRef,
      organizationRef: organizationRef,
      ownerRef: ownerRef,
      accountCode: accountCode,
      accountType: accountType.toDomain(),
      currency: currency,
      status: status.toDomain(),
      allowNegative: allowNegative,
      role: role.toDomain(),
      metadata: metadata,
      createdAt: createdAt,
      updatedAt: updatedAt,
      describable: newDescribable(
        name: name,
        description: mappedDescribable?.description,
      ),
      balance: balance?.toDomain(),
    );
  }
}

extension LedgerAccountModelMapper on LedgerAccount {
  LedgerAccountDTO toDTO() => LedgerAccountDTO(
    ledgerAccountRef: ledgerAccountRef,
    organizationRef: organizationRef,
    ownerRef: ownerRef,
    accountCode: accountCode,
    accountType: accountType.toDTO(),
    currency: currency,
    status: status.toDTO(),
    allowNegative: allowNegative,
    role: role.toDTO(),
    metadata: metadata,
    createdAt: createdAt,
    updatedAt: updatedAt,
    describable: describable.toDTO(),
    balance: balance?.toDTO(),
  );
}
