<?php

namespace App\Sms\Entity;

use App\Sms\Repository\SmsWalletRepository;
use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity(repositoryClass: SmsWalletRepository::class)]
#[ORM\Table(name: 'sms_wallets')]
#[ORM\UniqueConstraint(name: 'uniq_sms_wallet_entity', columns: ['entity_type', 'entity_id'])]
class SmsWallet
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column(type: 'integer')]
    private ?int $id = null;

    #[ORM\Column(name: 'entity_type', type: 'string', length: 10)]
    private string $entityType;

    #[ORM\Column(name: 'entity_id', type: 'integer')]
    private int $entityId;

    #[ORM\Column(name: 'balance_rials', type: 'integer')]
    private int $balanceRials = 0;

    #[ORM\Column(name: 'created_at', type: 'integer')]
    private int $createdAt;

    #[ORM\Column(name: 'updated_at', type: 'integer')]
    private int $updatedAt;

    public function __construct(string $entityType, int $entityId)
    {
        $this->entityType = $entityType;
        $this->entityId   = $entityId;
        $this->createdAt  = time();
        $this->updatedAt  = time();
    }

    public function getId(): ?int       { return $this->id; }
    public function getEntityType(): string { return $this->entityType; }
    public function getEntityId(): int  { return $this->entityId; }
    public function getBalanceRials(): int { return $this->balanceRials; }

    public function credit(int $amount): void
    {
        $this->balanceRials += $amount;
        $this->updatedAt = time();
    }

    public function debit(int $amount): bool
    {
        if ($this->balanceRials < $amount) {
            return false;
        }
        $this->balanceRials -= $amount;
        $this->updatedAt = time();
        return true;
    }
}
