<?php

namespace App\Modules\Integrations\Platform\Services;

use App\Models\User;
use App\Modules\Integrations\Platform\Models\ApiToken;
use Illuminate\Support\Str;

final class ApiTokenService
{
    /**
     * @param  list<string>  $scopes
     * @return array{token: ApiToken, plain: string}
     */
    public function createToken(int $tenantId, string $name, array $scopes, ?User $createdBy = null, ?\DateTimeInterface $expiresAt = null): array
    {
        $plain = 'saas_' . Str::random(48);
        $hash = self::hashToken($plain);

        $token = ApiToken::query()->create([
            'tenant_id' => $tenantId,
            'created_by_user_id' => $createdBy?->id,
            'name' => $name,
            'token_hash' => $hash,
            'scopes' => array_values(array_unique($scopes)),
            'expires_at' => $expiresAt,
        ]);

        return ['token' => $token, 'plain' => $plain];
    }

    public static function hashToken(string $plain): string
    {
        $pepper = (string) config('app.key');

        return hash('sha256', $pepper.'|'.$plain);
    }
}

