/**
 * ============================================================
 * storage.ts — Supabase Storage 上传工具
 * ============================================================
 * 功能：上传本地截图/图片到 Supabase Storage，返回 public URL
 * Bucket：screenshots（需在 Supabase Dashboard 中手动创建并设为 public）
 * ============================================================
 */

import { readFile } from "node:fs/promises";
import path from "node:path";
import { supabase } from "./db.ts";

const BUCKET = "screenshots";

function mimeFromExt(filePath: string): string {
  const ext = path.extname(filePath).toLowerCase();
  switch (ext) {
    case ".webp": return "image/webp";
    case ".png": return "image/png";
    case ".gif": return "image/gif";
    default: return "image/jpeg";
  }
}

/**
 * 上传本地图片文件到 Supabase Storage
 * @param filePath  — 本地绝对路径
 * @param storagePath — Storage 内路径，如 "row-002/search-round-1/page.jpg"
 * @returns public URL
 */
export async function uploadScreenshot(
  filePath: string,
  storagePath: string,
): Promise<string> {
  const fileBuffer = await readFile(filePath);
  const contentType = mimeFromExt(filePath);

  const { error } = await supabase.storage
    .from(BUCKET)
    .upload(storagePath, fileBuffer, {
      contentType,
      upsert: true,
    });

  if (error) {
    throw new Error(`[storage] 上传失败 (${storagePath}): ${error.message}`);
  }

  const { data: urlData } = supabase.storage
    .from(BUCKET)
    .getPublicUrl(storagePath);

  return urlData.publicUrl;
}
