<?php
declare(strict_types=1);

require_once __DIR__ . '/../config/helpers.php';
require_once __DIR__ . '/../config/mercado_pago_helpers.php';

$data = ($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST' ? input_json() : $_GET;
$idMotorista = (int) ($data['id_motorista'] ?? $data['id_usuario'] ?? 0);
$redirect = (string) ($data['redirect'] ?? '') === '1';

if ($idMotorista <= 0) {
    json_fail('Motorista nao informado.');
}

try {
    $pdo = db();
    $stmt = $pdo->prepare('SELECT id FROM usuarios WHERE id = ? LIMIT 1');
    $stmt->execute([$idMotorista]);
    if (!$stmt->fetch()) {
        json_fail('Motorista nao encontrado.', 404);
    }

    $url = mp_oauth_authorization_url($pdo, $idMotorista, 'motorista');
    if ($redirect) {
        header('Location: ' . $url);
        exit;
    }

    json_ok(['authorization_url' => $url]);
} catch (Throwable $e) {
    json_fail('Erro ao iniciar conexao OAuth.', 500, ['error' => $e->getMessage()]);
}
