import type { MemberPayment } from '@core/payments/domain/entities/MemberPayment';
import { MemberPayment as MemberPaymentFactory, MemberPaymentStatus } from '@core/payments/domain/entities/MemberPayment';

import { PaymentsMemberPaymentOrmEntity } from '../entities/PaymentsMemberPaymentOrmEntity';
import {
  assertDate,
  assertEnumValue,
  assertNonEmptyString,
  assertNumber,
  assertOptionalDate,
} from '../schema/TypeOrmPaymentsSchemaGuards';

export class PaymentsMemberPaymentOrmMapper {
  toOrmEntity(domain: MemberPayment): PaymentsMemberPaymentOrmEntity {
    const entity = new PaymentsMemberPaymentOrmEntity();
    entity.id = domain.id;
    entity.feeId = domain.feeId;
    entity.driverId = domain.driverId;
    entity.amount = domain.amount;
    entity.platformFee = domain.platformFee;
    entity.netAmount = domain.netAmount;
    entity.status = domain.status;
    entity.dueDate = domain.dueDate;
    entity.paidAt = domain.paidAt ?? null;
    return entity;
  }

  toDomain(entity: PaymentsMemberPaymentOrmEntity): MemberPayment {
    const entityName = 'PaymentsMemberPayment';

    assertNonEmptyString(entityName, 'id', entity.id);
    assertNonEmptyString(entityName, 'feeId', entity.feeId);
    assertNonEmptyString(entityName, 'driverId', entity.driverId);
    assertNumber(entityName, 'amount', entity.amount);
    assertNumber(entityName, 'platformFee', entity.platformFee);
    assertNumber(entityName, 'netAmount', entity.netAmount);
    assertEnumValue(entityName, 'status', entity.status, Object.values(MemberPaymentStatus));
    assertDate(entityName, 'dueDate', entity.dueDate);
    assertOptionalDate(entityName, 'paidAt', entity.paidAt);

    return MemberPaymentFactory.rehydrate({
      id: entity.id,
      feeId: entity.feeId,
      driverId: entity.driverId,
      amount: entity.amount,
      platformFee: entity.platformFee,
      netAmount: entity.netAmount,
      status: entity.status,
      dueDate: entity.dueDate,
      ...(entity.paidAt !== null && entity.paidAt !== undefined ? { paidAt: entity.paidAt } : {}),
    });
  }
}
