<?php

namespace App\Services;

use App\Models\SocialAccount;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class SocialAuthService
{
    /**
     * Revoke the OAuth token for a given social account.
     * Mandatory for security compliance.
     */
    public function revokeToken(SocialAccount $account): bool
    {
        if (!$account->token) {
            return false;
        }

        try {
            if ($account->provider === 'google') {
                $response = Http::asForm()->post('https://oauth2.googleapis.com/revoke', [
                    'token' => $account->token,
                ]);

                if ($response->successful()) {
                    Log::info("Successfully revoked Google token for User ID: {$account->user_id}");
                    $account->update([
                        'token' => null,
                        'refresh_token' => null,
                        'expires_at' => null,
                    ]);
                    return true;
                }
                
                Log::error("Failed to revoke Google token for User ID: {$account->user_id}. Status: " . $response->status());
            }
        } catch (\Exception $e) {
            Log::error("Error during token revocation: " . $e->getMessage());
        }

        return false;
    }
}
