<?php

namespace App\Document;

use App\Document\Chart;
use Doctrine\Common\Collections\Collection;
use Doctrine\Bundle\MongoDBBundle\Validator\Constraints\Unique as MongoDBUnique;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
use Symfony\Component\Validator\Constraints as Assert;

#[MongoDB\Document(collection: 'users')]
#[MongoDB\Unique(fields: 'email')]
class User implements UserInterface, PasswordAuthenticatedUserInterface
{
    /**
     * @MongoDB\Id
     */
    #[MongoDB\Id]
    protected string $id;

    #[MongoDB\Field(type: 'string')]
    #[Assert\NotBlank]
    #[Assert\Email]
    protected string $email;

    #[MongoDB\Field(type: 'string')]
    #[Assert\NotBlank]
    private string $password;

    #[MongoDB\Field(type: 'collection')]
    private array $roles = ['ROLE_USER'];

    #[MongoDB\ReferenceMany(targetDocument: Chart::class, mappedBy: "user")]
    protected $charts;

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

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

    public function setEmail(string $email): self
    {
        $this->email = $email;
        return $this;
    }

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

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

        return $this;
    }

    /**
     * @return Collection<int, Chart>
     */
    public function getCharts(): Collection
    {
        return $this->charts;
    }

    /**
     * Adds a chart to the user.
     *
     * @param Chart $chart The chart to add
     */
    public function addChart(Chart $chart): void
    {
        // Check if the chart already exists in the collection
        if (!$this->charts->contains($chart)) {
            // Add the chart to the collection
            $this->charts->add($chart);
            // Set the user reference in the chart entity
            $chart->setUser($this);
        }
    }

    public function getRoles(): array
    {
        $roles = $this->roles;
        // guarantee every user at least has ROLE_USER
        $roles[] = 'ROLE_USER';

        return array_unique($roles);
    }

    public function setRoles(array $roles): self
    {
        $this->roles = $roles;

        return $this;
    }


    public function eraseCredentials(): void
    {
        // $this->password = null;
    }


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


}