<?php

namespace App\Auth\Entity;

use Doctrine\ORM\Mapping as ORM;
use App\Auth\Repository\UserRepository;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Uid\Uuid;

#[ORM\Entity(repositoryClass: UserRepository::class)]
#[ORM\Table(name: 'users')]
#[ORM\UniqueConstraint(name: 'uniq_mobile', columns: ['mobile_number'])]
#[ORM\Index(columns: ['status'], name: 'idx_users_status')]
class User implements UserInterface, PasswordAuthenticatedUserInterface
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column(type: 'integer')]
    private ?int $id = null;

    #[ORM\Column(type: 'string', length: 36, unique: true)]
    private string $uuid;

    #[ORM\Column(name: 'mobile_number', type: 'string', length: 20, unique: true)]
    private string $mobileNumber;

    #[ORM\Column(name: 'password_hash', type: 'string', length: 255, nullable: true)]
    private ?string $passwordHash = null;

    #[ORM\Column(type: 'string', length: 100, nullable: true, unique: true)]
    private ?string $email = null;

    #[ORM\Column(name: 'real_name', type: 'string', length: 100, nullable: true)]
    private ?string $realName = null;

    #[ORM\Column(name: 'national_code', type: 'string', length: 10, nullable: true, unique: true)]
    private ?string $nationalCode = null;

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

    #[ORM\Column(type: 'json')]
    private array $roles = ['ROLE_USER'];

    #[ORM\Column(type: 'smallint')]
    private int $status = 1;

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

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

    public function __construct(string $mobileNumber)
    {
        $this->uuid         = Uuid::v4()->toRfc4122();
        $this->mobileNumber = $mobileNumber;
        $this->createdAt    = time();
        $this->updatedAt    = time();
    }

    public function getId(): ?int          { return $this->id; }
    public function getUuid(): string      { return $this->uuid; }
    public function getMobileNumber(): string { return $this->mobileNumber; }
    public function getEmail(): ?string    { return $this->email; }
    public function getRealName(): ?string { return $this->realName; }
    public function getNationalCode(): ?string { return $this->nationalCode; }
    public function isNationalCodeVerified(): bool { return $this->nationalCodeVerified; }
    public function getStatus(): int       { return $this->status; }
    public function getCreatedAt(): int    { return $this->createdAt; }

    public function getPassword(): ?string { return $this->passwordHash; }
    public function getPasswordHash(): ?string { return $this->passwordHash; }

    public function getRoles(): array
    {
        $roles = $this->roles;
        if (!in_array('ROLE_USER', $roles, true)) {
            $roles[] = 'ROLE_USER';
        }
        return array_unique($roles);
    }

    public function getUserIdentifier(): string { return $this->mobileNumber; }
    public function eraseCredentials(): void {}

    /** موبایل همان شناسه ورود است؛ تغییر آن نام‌کاربری کاربر را نیز تغییر می‌دهد. یکتایی در سطح فراخوان بررسی شود. */
    public function setMobileNumber(string $mobileNumber): self { $this->mobileNumber = $mobileNumber; $this->updatedAt = time(); return $this; }
    public function setEmail(?string $email): self           { $this->email = $email; return $this; }
    public function setRealName(?string $name): self         { $this->realName = $name; $this->updatedAt = time(); return $this; }
    public function setNationalCode(?string $code): self
    {
        $normalized = $code !== null && $code !== '' ? $code : null;
        if ($normalized !== $this->nationalCode) {
            $this->nationalCodeVerified = false;   // تغییر کد ملی، تأیید قبلی را باطل می‌کند
        }
        $this->nationalCode = $normalized;
        $this->updatedAt = time();
        return $this;
    }
    public function setNationalCodeVerified(bool $v): self { $this->nationalCodeVerified = $v; $this->updatedAt = time(); return $this; }
    public function setPasswordHash(?string $hash): self     { $this->passwordHash = $hash; $this->updatedAt = time(); return $this; }
    public function setRoles(array $roles): self             { $this->roles = $roles; $this->updatedAt = time(); return $this; }
    public function setStatus(int $status): self             { $this->status = $status; $this->updatedAt = time(); return $this; }

    public function addRole(string $role): self
    {
        if (!in_array($role, $this->roles, true)) {
            $this->roles[] = $role;
            $this->updatedAt = time();
        }
        return $this;
    }

    public function hasRole(string $role): bool
    {
        return in_array($role, $this->getRoles(), true);
    }

    public function isStaff(): bool
    {
        return $this->hasRole('ROLE_DOCTOR')
            || $this->hasRole('ROLE_CLINIC')
            || $this->hasRole('ROLE_SECRETARY')
            || $this->hasRole('ROLE_ADMIN')
            || $this->hasRole('ROLE_REPRESENTATION') // نماینده — لاگین با نام‌کاربری/رمز مجاز است
            || $this->hasRole('ROLE_IMPORTER'); // کاربر سیستمی کرالر — لاگین با رمز؛ دسترسی فقط اندپوینت ایمپورت
    }
}
