<?php

require_once __DIR__ . '/../config/database.php';

// Guarded so a test harness can supply an alternative backend (a local Postgres,
// for instance) by declaring these before this file is required. Production
// behaviour is unchanged: nothing else declares them.
if (!function_exists('supabase')) {
    function supabase(?string $token = null): SupabaseClient {
        return new SupabaseClient($token);
    }
}

if (!function_exists('supabaseService')) {
    function supabaseService(): SupabaseClient {
        return new SupabaseClient(null, true);
    }
}

if (!function_exists('supabaseRpc')) {
function supabaseRpc(string $functionName, array $params = []): ?array {
    $url = SUPABASE_REST . '/rpc/' . $functionName;
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'apikey: ' . SUPABASE_SERVICE_KEY,
        'Authorization: Bearer ' . SUPABASE_SERVICE_KEY,
        'Content-Type: application/json'
    ]);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    $result = curl_exec($ch);
    return json_decode($result, true);
}

}

function supabaseAuth(string $method, string $endpoint, ?array $body = null, ?string $token = null): array {
    $url = SUPABASE_AUTH . '/' . $endpoint;
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);

    $headers = [
        'apikey: ' . SUPABASE_ANON_KEY,
        'Content-Type: application/json'
    ];
    if ($token) {
        $headers[] = 'Authorization: Bearer ' . $token;
    }
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    if ($method === 'POST') {
        curl_setopt($ch, CURLOPT_POST, true);
        if ($body) curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
    }

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    $decoded = json_decode($response, true);
    if ($httpCode >= 400) {
        return ['error' => $decoded['error_description'] ?? $decoded['msg'] ?? $decoded['message'] ?? 'Auth error', 'code' => $httpCode];
    }
    return $decoded ?? [];
}
