<?php

namespace App\Services;

use App\Models\ApiClient;
use App\Models\User;
use Illuminate\Support\Str;

class ApiCredentialService
{
    public function ensureDefaultClient(User $user): ApiClient
    {
        $existing = ApiClient::query()->where('user_id', $user->id)->orderBy('id')->first();
        if ($existing) {
            return $existing;
        }

        [$publicKey, $secret] = $this->generateKeyPair();

        return ApiClient::query()->create([
            'user_id' => $user->id,
            'name' => 'Default API Client',
            'public_key' => $publicKey,
            'secret' => $secret,
            'secret_last4' => substr($secret, -4),
            'status' => 'active',
            'rate_limit_per_minute' => 120,
        ]);
    }

    /**
     * @return array{0: ApiClient, 1: string}
     */
    public function rotateSecret(ApiClient $client): array
    {
        [, $secret] = $this->generateKeyPair();

        $client->forceFill([
            'secret' => $secret,
            'secret_last4' => substr($secret, -4),
            'rotated_at' => now(),
            'status' => 'active',
        ])->save();

        return [$client->fresh(), $secret];
    }

    /**
     * @return array{0: string, 1: string}
     */
    public function generateKeyPair(): array
    {
        return [
            'vtu_pk_'.Str::lower(Str::random(30)),
            'vtu_sk_'.Str::lower(Str::random(48)),
        ];
    }
}
