<?php

use Illuminate\Support\Facades\Route;

use App\Services\BlingClient;
use App\Models\IntegrationLog;
use Illuminate\Http\Request;

Route::get('/', function () {
    return view('welcome');
});

// Fluxo OAuth do Bling (web)
Route::get('/bling/authorize', function (BlingClient $bling) {
    return redirect()->away($bling->buildAuthUrl());
});

Route::get('/bling/callback', function (Request $request, BlingClient $bling) {
    $code = $request->query('code');
    $state = $request->query('state');
    $expected = env('BLING_OAUTH_STATE');

    if ($expected && $state && $state !== $expected) {
        IntegrationLog::write('bling_state_mismatch', ['received' => $state, 'expected' => $expected]);
        return response()->json(['ok' => false, 'error' => 'Invalid state'], 400);
    }

    if (!$code) {
        return response()->json(['ok' => false, 'error' => 'Missing code'], 400);
    }

    try {
        $token = $bling->authorizeWithCode($code);
        IntegrationLog::write('bling_authorized', ['token_id' => $token->id]);
        return response()->json(['ok' => true, 'token_id' => $token->id]);
    } catch (\Throwable $e) {
        IntegrationLog::write('bling_authorize_failed', ['error' => $e->getMessage()]);
        return response()->json(['ok' => false, 'error' => $e->getMessage()], 500);
    }
});
