import { MonitoredAddress as PrismaMonitoredAddress } from '@prisma/client';
import { MonitoredAddress, MonitoredAddressProps } from '@/domain/aggregates/monitored-address';
import { ChainType, EvmAddress } from '@/domain/value-objects';

export class MonitoredAddressMapper {
  /**
   * Map from Prisma to Domain (only for USER addresses)
   * System addresses are handled separately
   */
  static toDomain(prisma: PrismaMonitoredAddress): MonitoredAddress {
    // For USER addresses, accountSequence and userId must exist
    if (!prisma.accountSequence || !prisma.userId) {
      throw new Error(`MonitoredAddress ${prisma.id} missing accountSequence or userId`);
    }

    const props: MonitoredAddressProps = {
      id: prisma.id,
      chainType: ChainType.create(prisma.chainType),
      address: EvmAddress.fromUnchecked(prisma.address),
      accountSequence: prisma.accountSequence,
      userId: prisma.userId,
      isActive: prisma.isActive,
      createdAt: prisma.createdAt,
      updatedAt: prisma.updatedAt,
    };

    return MonitoredAddress.reconstitute(props);
  }

  static toPersistence(
    domain: MonitoredAddress,
  ): Omit<PrismaMonitoredAddress, 'id' | 'createdAt' | 'updatedAt'> & { id?: bigint } {
    return {
      id: domain.id,
      chainType: domain.chainType.toString(),
      address: domain.address.lowercase,
      addressType: 'USER',
      accountSequence: domain.accountSequence,
      userId: domain.userId,
      systemAccountType: null,
      systemAccountId: null,
      regionCode: null,
      isActive: domain.isActive,
    };
  }
}
