<?php

declare(strict_types=1);

namespace Australcode\Rewards\Domain\Wallet;

defined( 'ABSPATH' ) || exit;

/**
 * Denormalized per-user balance (one row in wp_acrwd_balances). Kept in sync
 * by WalletService on every ledger movement so reads are O(1).
 */
final class Balance {

	public function __construct(
		public readonly int $user_id,
		public readonly int $points_balance = 0,
		public readonly int $lifetime_earned = 0,
		public readonly int $lifetime_redeemed = 0,
		public readonly string $tier_id = '',
		public readonly ?string $updated_at = null,
	) {
	}

	public static function empty( int $user_id ): self {
		return new self( user_id: $user_id );
	}

	/**
	 * @param array<string,mixed> $row
	 */
	public static function from_row( array $row ): self {
		return new self(
			user_id: (int) ( $row['user_id'] ?? 0 ),
			points_balance: (int) ( $row['points_balance'] ?? 0 ),
			lifetime_earned: (int) ( $row['lifetime_earned'] ?? 0 ),
			lifetime_redeemed: (int) ( $row['lifetime_redeemed'] ?? 0 ),
			tier_id: (string) ( $row['tier_id'] ?? '' ),
			updated_at: isset( $row['updated_at'] ) ? (string) $row['updated_at'] : null,
		);
	}

	/**
	 * @return array<string,mixed>
	 */
	public function to_row(): array {
		return array(
			'user_id'           => $this->user_id,
			'points_balance'    => $this->points_balance,
			'lifetime_earned'   => $this->lifetime_earned,
			'lifetime_redeemed' => $this->lifetime_redeemed,
			'tier_id'           => $this->tier_id,
		);
	}
}
