<?php

namespace App\Security;

class PasswordGenerator
{
    private int $length;
    private string $charsLower = 'abcdefghijklmnopqrstuvwxyz';
    private string $charsUpper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    private string $digits = '0123456789';
    private string $specials = '@#_-';  // Caractères spéciaux limités

    public function __construct(int $length = 12)
    {
        if ($length < 4) {
            throw new \InvalidArgumentException('La longueur du mot de passe doit être au moins 4.');
        }
        $this->length = $length;
    }

    public function generate(): string
    {
        // Garantir la présence d'au moins un caractère de chaque type
        $password = [
            $this->randomChar($this->charsLower),
            $this->randomChar($this->charsUpper),
            $this->randomChar($this->digits),
            $this->randomChar($this->specials),
        ];

        $allChars = $this->charsLower . $this->charsUpper . $this->digits . $this->specials;

        for ($i = 4; $i < $this->length; $i++) {
            $password[] = $this->randomChar($allChars);
        }

        shuffle($password);

        return implode('', $password);
    }

    private function randomChar(string $chars): string
    {
        return $chars[random_int(0, strlen($chars) - 1)];
    }
}
