<?php declare(strict_types=1);
/**
 * This file is part of the SplendidBear Websites' projects.
 *
 * Copyright (c) 2026 @ www.splendidbear.org
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace App\Entity;

use App\Repository\WebAuthnCredentialRepository;
use DateTime;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\GeneratedValue;
use Doctrine\ORM\Mapping\Id;
use Doctrine\ORM\Mapping\JoinColumn;
use Doctrine\ORM\Mapping\ManyToOne;
use Doctrine\ORM\Mapping\Table;
use JsonException;
use RuntimeException;

/**
 * Class WebAuthnCredential
 *
 * @package  App\Entity
 * @author   Lang <https://www.splendidbear.org>
 * @category Class
 * @license  https://www.gnu.org/licenses/lgpl-3.0.en.html GNU Lesser General Public License
 * @link     www.splendidbear.org
 * @since    2026. 04. 12.
 */
#[Entity(repositoryClass: WebAuthnCredentialRepository::class), Table(name: 'app_webauthn_credential')]
class WebAuthnCredential
{
    #[Id, GeneratedValue, Column]
    public private(set) ?int $id = null;

    #[ManyToOne(targetEntity: User::class)]
    #[JoinColumn(nullable: false, onDelete: 'CASCADE')]
    public ?User $user = null;

    #[Column(type: Types::TEXT)]
    public ?string $credentialData = null;

    #[Column(length: 255)]
    public ?string $credentialName = null;

    #[Column(type: Types::DATETIME_MUTABLE)]
    public ?DateTime $createdAt = null;

    #[Column(type: Types::DATETIME_MUTABLE, nullable: true)]
    public ?DateTime $lastUsedAt = null;

    #[Column]
    public bool $isBackupEligible = false;

    #[Column]
    public bool $isBackupAuthenticated = false;


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

    public function getPublicKeyCredentialSource()
    {
        if ($this->credentialData === null) {
            return null;
        }

        try {
            return json_decode($this->credentialData, true, 512, JSON_THROW_ON_ERROR);
        } catch (JsonException $e) {
            throw new RuntimeException("Unable to parse JSON: {$e->getMessage()}");
        }
    }

    public function setPublicKeyCredentialSource($source): self
    {
        try {
            $this->credentialData = is_array($source) ? json_encode($source, JSON_THROW_ON_ERROR) : (string)$source;
        } catch (JsonException $e) {
            throw new RuntimeException("Unable to encode JSON: {$e->getMessage()}");
        }

        return $this;
    }
}
