<?php

namespace App\Auth\Entity;

use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity]
#[ORM\Table(name: 'mobile_verification_otp')]
#[ORM\Index(columns: ['entity_type', 'entity_id'], name: 'idx_otp_entity')]
class MobileVerificationOtp
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column(type: 'integer')]
    private ?int $id = null;

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

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

    #[ORM\Column(name: 'new_mobile', type: 'string', length: 15)]
    private string $newMobile;

    #[ORM\Column(name: 'otp_code', type: 'string', length: 6)]
    private string $otpCode;

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

    #[ORM\Column(name: 'is_used', type: 'boolean')]
    private bool $isUsed = false;

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

    public function __construct(string $entityType, int $entityId, string $newMobile)
    {
        $this->entityType = $entityType;
        $this->entityId   = $entityId;
        $this->newMobile  = $newMobile;
        $this->otpCode    = str_pad((string) random_int(0, 999999), 6, '0', STR_PAD_LEFT);
        $this->expiresAt  = time() + 300; // 5 minutes
        $this->createdAt  = time();
    }

    public function getId(): ?int      { return $this->id; }
    public function getEntityType(): string { return $this->entityType; }
    public function getEntityId(): int  { return $this->entityId; }
    public function getNewMobile(): string { return $this->newMobile; }
    public function getOtpCode(): string   { return $this->otpCode; }
    public function isExpired(): bool      { return time() > $this->expiresAt; }
    public function isUsed(): bool         { return $this->isUsed; }

    public function markUsed(): void { $this->isUsed = true; }
}
