<?php
// app/storage.php
// Requer: SUPABASE_URL, SUPABASE_SERVICE_KEY e SUPABASE_BUCKET_FUNIL definidos em app/config.php

if (!defined('SUPABASE_URL'))         { throw new RuntimeException('SUPABASE_URL ausente no config'); }
if (!defined('SUPABASE_SERVICE_KEY')) { throw new RuntimeException('SUPABASE_SERVICE_KEY ausente no config'); }

function supa_http(string $method, string $url, array $headers = [], $body = null): array {
    $ch = curl_init($url);
    $h = array_merge([
        'Authorization: Bearer ' . SUPABASE_SERVICE_KEY,
    ], $headers);

    curl_setopt_array($ch, [
        CURLOPT_CUSTOMREQUEST   => strtoupper($method),
        CURLOPT_HTTPHEADER      => $h,
        CURLOPT_RETURNTRANSFER  => true,
        CURLOPT_FOLLOWLOCATION  => true,
        CURLOPT_MAXREDIRS       => 3,
        CURLOPT_TIMEOUT         => 30,
    ]);

    // Corpo (binário ou JSON)
    if ($body !== null) {
        // Se for array, envie como raw (já deve vir json_encode do caller)
        curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
    }

    $res    = curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $err    = curl_error($ch);
    curl_close($ch);

    return [$status, $res, $err];
}

/**
 * Faz upload (upsert) de um arquivo local para o Storage.
 * @param string $bucket ex.: 'funnel'
 * @param string $path   ex.: 'USER_ID/2025/09/arquivo.png'
 * @param string $filePath caminho local temporário (ex.: $_FILES['file']['tmp_name'])
 * @param string $contentType mime ex.: 'image/png'
 */
function supa_storage_upload(string $bucket, string $path, string $filePath, string $contentType): array {
    $url  = rtrim(SUPABASE_URL, '/') . "/storage/v1/object/{$bucket}/{$path}";
    $data = @file_get_contents($filePath);
    if ($data === false) {
        return ['ok' => false, 'error' => 'Falha ao ler arquivo temporário'];
    }

    [$st, $res, $err] = supa_http('POST', $url, [
        'Content-Type: ' . $contentType,
        'x-upsert: true',
    ], $data);

    if ($st >= 200 && $st < 300) {
        $j = json_decode($res, true);
        return ['ok' => true, 'data' => $j];
    }
    return ['ok' => false, 'status' => $st, 'error' => ($err ?: $res ?: 'Falha no upload')];
}

/** Retorna URL pública (para bucket PUBLIC) */
function supa_storage_public_url(string $bucket, string $path): string {
    return rtrim(SUPABASE_URL, '/') . "/storage/v1/object/public/{$bucket}/{$path}";
}

/**
 * Gera URL assinada (para bucket PRIVATE).
 * @param int $expires segundos (mínimo 60)
 */
function supa_storage_sign_url(string $bucket, string $path, int $expires = 3600): array {
    $url = rtrim(SUPABASE_URL, '/') . "/storage/v1/object/sign/{$bucket}/{$path}";
    $payload = json_encode(['expiresIn' => max(60, $expires)]);

    [$st, $res, $err] = supa_http('POST', $url, ['Content-Type: application/json'], $payload);
    if ($st >= 200 && $st < 300) {
        $j = json_decode($res, true);
        // dependendo da versão, a chave pode ser signedURL ou signedUrl
        $signed = $j['signedURL'] ?? $j['signedUrl'] ?? null;
        if ($signed) {
            return ['ok' => true, 'url' => rtrim(SUPABASE_URL, '/') . $signed];
        }
    }
    return ['ok' => false, 'status' => $st, 'error' => ($err ?: $res ?: 'Falha ao assinar URL')];
}
