<?php

namespace App\Services\Minimax;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;

class MinimaxAuthService
{
    /**
     * Get a valid OAuth2 bearer token for the given account.
     * Tokens are cached for 3500 seconds (just under the 1h expiry).
     */
    public function getToken(string $account): string
    {
        $cacheKey = "minimax_token_{$account}";

        return Cache::remember($cacheKey, 3500, function () use ($account) {
            return $this->fetchToken($account);
        });
    }

    private function fetchToken(string $account): string
    {
        $config = config("minimax.accounts.{$account}");

        if (!$config) {
            throw new \RuntimeException("Minimax account '{$account}' not configured.");
        }

        $baseUrl = rtrim($config['url'], '/');
        $tokenUrl = $baseUrl . '/aut/oauth20/token';

        $response = Http::asForm()->post($tokenUrl, [
            'grant_type'    => 'password',
            'client_id'     => $config['client_id'],
            'client_secret' => $config['client_secret'],
            'username'      => $config['username'],
            'password'      => $config['password'],
            'scope'         => $config['scope'],
        ]);

        if (!$response->successful()) {
            throw new \RuntimeException(
                "Minimax auth failed for account '{$account}': " . $response->body()
            );
        }

        $data = $response->json();

        if (empty($data['access_token'])) {
            throw new \RuntimeException(
                "Minimax auth returned no access_token for account '{$account}'."
            );
        }

        return $data['access_token'];
    }

    /**
     * Force-clear a cached token (call on 401 responses).
     */
    public function forgetToken(string $account): void
    {
        Cache::forget("minimax_token_{$account}");
    }
}
