<?php

namespace App\Integrations;

use App\Contracts\ProvidesIntegrationToken;
use App\Facades\Settings;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;

class AutosOnShow implements ProvidesIntegrationToken
{
    private const TOKEN_URL = 'https://br-api.aos.tv/token/';

    private function enabled(): bool
    {
        return (bool)Settings::get('image-sync-autos-on-show-enabled');
    }

    private function getConfig(): array
    {
        return [
            'enabled' => $this->enabled(),
            'client_id' => Settings::get('image-sync-autos-on-show-client_id'),
            'client_secret' => Settings::get('image-sync-autos-on-show-client_secret'),
        ];
    }

    public function getToken(): string
    {
        return Cache::remember('autos_on_show_token_' . tenant('id'), 3500, function () {
            $config = $this->getConfig();

            if (!$config['enabled'] || !$config['client_id'] || !$config['client_secret']) {
                throw new \Exception('Integration not enabled or missing credentials.');
            }

            $response = Http::asForm()
                ->post(self::TOKEN_URL, [
                    'grant_type'    => 'client_credentials',
                    'client_id' => $config['client_id'],
                    'client_secret' => $config['client_secret'],
                ]);

            if (!$response->successful()) {
                throw new \Exception(
                    'Failed to fetch token: ' . $response->status() . ' - ' . $response->body()
                );
            }

            return $response['access_token'];
        });
    }
}
