<?php

namespace App\Http\Controllers;

use App\Models\UpworkToken;
use App\Services\UpworkAdapter;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

/**
 * ─── UPWORK OAUTH2 CONTROLLER — SKELETON ────────────────────────────────────
 *
 * Para activar:
 * 1. Configura en config/services.php:
 *      'upwork' => [
 *          'client_id'     => env('UPWORK_CLIENT_ID'),
 *          'client_secret' => env('UPWORK_CLIENT_SECRET'),
 *          'redirect_uri'  => env('UPWORK_REDIRECT_URI'),
 *      ],
 *
 * 2. Agrega en .env:
 *      UPWORK_CLIENT_ID=your_client_id
 *      UPWORK_CLIENT_SECRET=your_client_secret
 *      UPWORK_REDIRECT_URI=http://localhost:8080/upwork/callback
 *
 * 3. En Filament (ej: SystemSettingResource o un Panel personalizado),
 *    agrega un botón que apunte a route('upwork.connect').
 *
 * Documentación: https://developers.upwork.com/#authentication_oauth-2-0
 * ────────────────────────────────────────────────────────────────────────────
 */
class UpworkOAuthController extends Controller
{
    /**
     * Paso 1: Redirigir al usuario a Upwork para autorizar.
     * Ruta: GET /upwork/connect
     */
    public function redirect(): RedirectResponse
    {
        $adapter = new UpworkAdapter();
        $url     = $adapter->getAuthorizationUrl();

        // TODO: en producción, verificar el `state` para prevenir CSRF.
        return redirect($url);
    }

    /**
     * Paso 2: Upwork redirige aquí con el `code` de autorización.
     * Ruta: GET /upwork/callback
     */
    public function callback(Request $request): RedirectResponse
    {
        if ($request->has('error')) {
            return redirect('/admin')
                ->with('error', 'Autorización rechazada: ' . $request->get('error_description'));
        }

        $code    = $request->get('code');
        $adapter = new UpworkAdapter();

        try {
            // TODO: implementar en UpworkAdapter::exchangeCodeForToken() con credenciales reales.
            $tokenData = $adapter->exchangeCodeForToken($code);

            UpworkToken::updateOrCreate(
                ['user_id' => auth()->id()],
                [
                    'access_token'  => $tokenData['access_token'],
                    'refresh_token' => $tokenData['refresh_token'] ?? null,
                    'token_type'    => $tokenData['token_type'] ?? 'Bearer',
                    'expires_at'    => now()->addSeconds($tokenData['expires_in'] ?? 86400),
                ]
            );

            return redirect('/admin')->with('success', 'Cuenta Upwork conectada correctamente.');
        } catch (\Throwable $e) {
            return redirect('/admin')->with('error', 'Error conectando Upwork: ' . $e->getMessage());
        }
    }
}
