<?php

namespace App\Services\Photobooth;

use App\Models\Event;

class CredentialGenerator
{
    public function __construct(
        private readonly int $usernameLength = 8,
        private readonly int $passwordLength = 8,
        private readonly string $usernamePrefix = 'pb'
    ) {}

    public function generateUsername(Event $event): string
    {
        $maxLength = min(10, max(6, $this->usernameLength));
        $prefix = substr($this->usernamePrefix, 0, $maxLength - 3);
        $tenantMarker = strtoupper(substr($event->tenant?->slug ?? $event->tenant?->name ?? 'x', 0, 1));

        $remaining = $maxLength - strlen($prefix) - 1;
        $randomSegment = $this->randomSegment(max(3, $remaining));

        return strtoupper($prefix.$tenantMarker.substr($randomSegment, 0, $remaining));
    }

    public function generatePassword(): string
    {
        $length = min(8, max(6, $this->passwordLength));

        return $this->randomSegment($length);
    }

    protected function randomSegment(int $length): string
    {
        $alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
        $poolSize = strlen($alphabet);
        $value = '';

        for ($i = 0; $i < $length; $i++) {
            $value .= $alphabet[random_int(0, $poolSize - 1)];
        }

        return $value;
    }
}
