<?php

namespace NoahVet\Reef\Security\User;

use NoahVet\Reef\Jane\Model\UserinfoGetResponse200;
use Symfony\Component\Security\Core\User\UserInterface;

class ReefOAuthUser implements UserInterface
{
    public const PRINCIPAL_PREFIX = 'reef:iam:principal:';

    protected string $id;

    protected string $uuid;

    public function __construct(
        string $id,
        protected ?string $email = null,
        protected ?UserinfoGetResponse200 $userinfo = null,
    ) {
        if (!\str_starts_with($id, self::PRINCIPAL_PREFIX)) {
            $this->id = self::PRINCIPAL_PREFIX.$id;
            $this->uuid = $id;
        } else {
            $this->id = $id;
            $this->uuid = \str_replace(self::PRINCIPAL_PREFIX, '', $id);
        }
    }

    #[\Override]
    public function getRoles(): array
    {
        return ['ROLE_REEF_USER'];
    }

    #[\Override]
    public function eraseCredentials(): void
    {
        // No credential stored
    }

    #[\Override]
    public function getUserIdentifier(): string
    {
        return $this->id;
    }

    /**
     * @deprecated since Symfony 5.3
     */
    public function getPassword(): ?string
    {
        return null;
    }

    /**
     * @deprecated since Symfony 5.3
     */
    public function getSalt(): ?string
    {
        return null;
    }

    /**
     * @deprecated since Symfony 5.3
     */
    public function getUsername(): ?string
    {
        return $this->getUserIdentifier();
    }

    public function getUuid(): string
    {
        return $this->uuid;
    }

    public function getUserinfo(): ?UserinfoGetResponse200
    {
        return $this->userinfo;
    }

    public function getFirstname(): ?string
    {
        return $this->userinfo?->getGivenName();
    }

    public function getLastname(): ?string
    {
        return $this->userinfo?->getFamilyName();
    }

    public function getFullname(): ?string
    {
        return $this->userinfo?->getDisplayName();
    }

    public static function createFromUserinfo(UserinfoGetResponse200 $userinfo): self
    {
        return new self(
            $userinfo->getIdentifier(),
            $userinfo->getEmail(),
            $userinfo,
        );
    }
}
