<?php

namespace App\Entity;

use App\Repository\UserRepository;
use Doctrine\ORM\Mapping as ORM;
use Scheb\TwoFactorBundle\Model\BackupCodeInterface;
use Scheb\TwoFactorBundle\Model\Email\TwoFactorInterface as EmailTwoFactorInterface;
use Scheb\TwoFactorBundle\Model\Google\TwoFactorInterface as GoogleTwoFactorInterface;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;
use Vich\UploaderBundle\Mapping\Attribute as Vich;

#[ORM\Entity(repositoryClass: UserRepository::class)]
#[ORM\Table(name: '`user`')]
#[UniqueEntity(fields: ['email'], message: 'Un compte existe déjà avec cet email.')]
#[Vich\Uploadable]
class User implements UserInterface, PasswordAuthenticatedUserInterface, EmailTwoFactorInterface, GoogleTwoFactorInterface, BackupCodeInterface
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    private ?int $id = null;

    #[ORM\Column(length: 180, unique: true)]
    #[Assert\Email(message: 'L\'adresse email n\'est pas valide.')]
    #[Assert\NotBlank(message: 'L\'email est requis.')]
    private ?string $email = null;

    #[ORM\Column(length: 255)]
    private ?string $firstName = null;

    #[ORM\Column(length: 255)]
    private ?string $lastName = null;

    /** @var list<string> */
    #[ORM\Column]
    private array $roles = [];

    #[ORM\Column]
    private ?string $password = null;

    #[ORM\Column(length: 255, nullable: true)]
    private ?string $avatar = null;

    #[Vich\UploadableField(mapping: 'user_avatar', fileNameProperty: 'avatar')]
    #[Assert\Image(maxSize: '2M', mimeTypes: ['image/jpeg', 'image/png', 'image/webp'])]
    private ?File $avatarFile = null;

    #[ORM\Column(nullable: true)]
    private ?\DateTimeImmutable $updatedAt = null;

    #[ORM\Column(length: 255, nullable: true, unique: true)]
    private ?string $keycloakId = null;

    #[ORM\Column(length: 255, nullable: true)]
    private ?string $tempPassword = null;

    #[ORM\Column(nullable: true)]
    private ?string $emailAuthCode = null;

    #[ORM\Column(options: ['default' => false])]
    private bool $isEmailAuthEnabled = false;

    #[ORM\Column(length: 255, nullable: true)]
    private ?string $googleAuthenticatorSecret = null;

    #[ORM\Column(options: ['default' => false])]
    private bool $isGoogleAuthEnabled = false;

    /** @var list<string> */
    #[ORM\Column(type: 'json', nullable: true)]
    private ?array $backupCodes = null;

    #[ORM\Column]
    private \DateTimeImmutable $createdAt;

    public function __construct()
    {
        $this->createdAt = new \DateTimeImmutable();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getEmail(): ?string
    {
        return $this->email;
    }

    public function setEmail(string $email): static
    {
        $this->email = $email;

        return $this;
    }

    public function getFirstName(): ?string
    {
        return $this->firstName;
    }

    public function setFirstName(string $firstName): static
    {
        $this->firstName = $firstName;

        return $this;
    }

    public function getLastName(): ?string
    {
        return $this->lastName;
    }

    public function setLastName(string $lastName): static
    {
        $this->lastName = $lastName;

        return $this;
    }

    public function getFullName(): string
    {
        return $this->firstName.' '.$this->lastName;
    }

    public function getUserIdentifier(): string
    {
        return (string) $this->email;
    }

    /** @return list<string> */
    public function getRoles(): array
    {
        $roles = $this->roles;
        $roles[] = 'ROLE_USER';

        return array_unique($roles);
    }

    /** @param list<string> $roles */
    public function setRoles(array $roles): static
    {
        $this->roles = $roles;

        return $this;
    }

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

    public function setPassword(string $password): static
    {
        $this->password = $password;

        return $this;
    }

    public function eraseCredentials(): void
    {
        // Required by UserInterface — no sensitive data to clear in this implementation
    }

    /** @return array<string, mixed> */
    public function __serialize(): array
    {
        return [
            'id' => $this->id,
            'email' => $this->email,
            'password' => $this->password,
            'roles' => $this->roles,
            'firstName' => $this->firstName,
            'lastName' => $this->lastName,
        ];
    }

    /** @param array<string, mixed> $data */
    public function __unserialize(array $data): void
    {
        $this->id = $data['id'];
        $this->email = $data['email'];
        $this->password = $data['password'];
        $this->roles = $data['roles'];
        $this->firstName = $data['firstName'];
        $this->lastName = $data['lastName'];
    }

    public function getTempPassword(): ?string
    {
        return $this->tempPassword;
    }

    public function setTempPassword(?string $tempPassword): static
    {
        $this->tempPassword = $tempPassword;

        return $this;
    }

    public function hasTempPassword(): bool
    {
        return null !== $this->tempPassword;
    }

    public function clearTempPassword(): static
    {
        $this->tempPassword = null;

        return $this;
    }

    public function getAvatar(): ?string
    {
        return $this->avatar;
    }

    public function setAvatar(?string $avatar): static
    {
        $this->avatar = $avatar;

        return $this;
    }

    public function getAvatarFile(): ?File
    {
        return $this->avatarFile;
    }

    public function setAvatarFile(?File $avatarFile): static
    {
        $this->avatarFile = $avatarFile;

        if (null !== $avatarFile) {
            $this->updatedAt = new \DateTimeImmutable();
        }

        return $this;
    }

    public function getUpdatedAt(): ?\DateTimeImmutable
    {
        return $this->updatedAt;
    }

    // --- Email 2FA ---

    public function isEmailAuthEnabled(): bool
    {
        return $this->isEmailAuthEnabled && null === $this->keycloakId;
    }

    public function setIsEmailAuthEnabled(bool $enabled): static
    {
        $this->isEmailAuthEnabled = $enabled;

        return $this;
    }

    /** @SuppressWarnings("PHPMD.DuplicatedCode") — required by EmailTwoFactorInterface */
    public function getEmailAuthRecipient(): string
    {
        return $this->getUserIdentifier();
    }

    public function getEmailAuthCode(): ?string
    {
        return $this->emailAuthCode;
    }

    public function setEmailAuthCode(string $authCode): void
    {
        $this->emailAuthCode = $authCode;
    }

    // --- Google Authenticator 2FA ---

    public function isGoogleAuthenticatorEnabled(): bool
    {
        return $this->isGoogleAuthEnabled && null !== $this->googleAuthenticatorSecret && null === $this->keycloakId;
    }

    public function setIsGoogleAuthEnabled(bool $enabled): static
    {
        $this->isGoogleAuthEnabled = $enabled;

        return $this;
    }

    /** @SuppressWarnings("PHPMD.DuplicatedCode") — required by GoogleTwoFactorInterface */
    public function getGoogleAuthenticatorUsername(): string
    {
        return $this->getUserIdentifier();
    }

    public function getGoogleAuthenticatorSecret(): ?string
    {
        return $this->googleAuthenticatorSecret;
    }

    public function setGoogleAuthenticatorSecret(?string $secret): static
    {
        $this->googleAuthenticatorSecret = $secret;

        return $this;
    }

    // --- Backup Codes ---

    public function isBackupCode(string $code): bool
    {
        return null !== $this->backupCodes && \in_array($code, $this->backupCodes, true);
    }

    public function invalidateBackupCode(string $code): void
    {
        if (null === $this->backupCodes) {
            return;
        }

        $key = array_search($code, $this->backupCodes, true);
        if (false !== $key) {
            unset($this->backupCodes[$key]);
            $this->backupCodes = array_values($this->backupCodes);
        }
    }

    /** @return list<string> */
    public function getBackupCodes(): array
    {
        return $this->backupCodes ?? [];
    }

    /** @param list<string> $codes */
    public function setBackupCodes(array $codes): static
    {
        $this->backupCodes = $codes;

        return $this;
    }

    public function generateBackupCodes(int $count = 8): static
    {
        $codes = [];
        for ($i = 0; $i < $count; ++$i) {
            $codes[] = bin2hex(random_bytes(4));
        }
        $this->backupCodes = $codes;

        return $this;
    }

    // --- Keycloak ---

    public function getKeycloakId(): ?string
    {
        return $this->keycloakId;
    }

    public function setKeycloakId(?string $keycloakId): static
    {
        $this->keycloakId = $keycloakId;

        return $this;
    }

    public function getCreatedAt(): \DateTimeImmutable
    {
        return $this->createdAt;
    }
}
