<?php

declare(strict_types=1);

/*
 * This file is part of the Serenity package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Serenity\CoreBundle\Shared\ValueObject;

use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;

#[ORM\Embeddable]
final class Password implements \Stringable
{
    public const string ALGO = \PASSWORD_BCRYPT;
    public const array OPTIONS = ['cost' => 12];

    #[ORM\Column(name: 'password', type: Types::STRING)]
    public string $value;

    public string $plainPassword;

    public function __construct(#[\SensitiveParameter] ?string $plainPassword = null, bool $test = false)
    {
        if (!$plainPassword) {
            $plainPassword = $this->random_password();
        }

        $this->plainPassword = $plainPassword;
        $this->value = $this->plainPassword;
        if (!$test) {
            $this->value = password_hash($this->plainPassword, self::ALGO, self::OPTIONS);
        }
    }

    public function isEqualTo(self $password): bool
    {
        return $password->value === $this->value;
    }

    public function __toString(): string
    {
        return $this->value;
    }

    public function random_password(): string
    {
        $random_characters = 2;

        $lower_case = 'abcdefghijklmnopqrstuvwxyz';
        $upper_case = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $numbers = '1234567890';
        $symbols = '!@&';

        $lower_case = str_shuffle($lower_case);
        $upper_case = str_shuffle($upper_case);
        $numbers = str_shuffle($numbers);
        $symbols = str_shuffle($symbols);

        $random_password = mb_substr($lower_case, 0, $random_characters);
        $random_password .= mb_substr($upper_case, 0, $random_characters);
        $random_password .= mb_substr($numbers, 0, $random_characters);
        $random_password .= mb_substr($symbols, 0, $random_characters);

        return str_shuffle($random_password);
    }
}
