<?php

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

function supabase(?string $token = null): SupabaseClient {
    return new SupabaseClient($token);
}

function supabaseService(): SupabaseClient {
    return new SupabaseClient(null, true);
}

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);
    curl_close($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);
    curl_close($ch);

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