/**
 * product-image-generate
 * 通过统一 AI Provider 适配层生成产品图，上传到 Storage 返回公开 URL。
 * Provider/模型由 ai_provider_configs 表的 purpose='product_image' 行控制。
 *
 * Body: { name: string; description?: string; extraPrompt?: string; style?: string }
 * Resp: { url: string; path: string; provider: string; model: string }
 */
import { createClient } from "https://esm.sh/@supabase/supabase-js@2.45.0";
import { corsHeaders, handlePreflight } from "../_shared/cors.ts";
import { generateImage, loadProviderConfig, base64ToBytes } from "../_shared/aiProvider.ts";

const SUPABASE_URL = Deno.env.get("SUPABASE_URL")!;
const SERVICE_ROLE = Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!;

function json(data: unknown, status = 200) {
  return new Response(JSON.stringify(data), {
    status,
    headers: { ...corsHeaders, "Content-Type": "application/json" },
  });
}

/** 兜底风格预设（DB 不可用时使用） */
const FALLBACK_PRESETS: Record<string, string> = {
  studio_white:
    "Studio lighting, clean pure white seamless background, centered composition, subtle soft shadow underneath, catalog-style product shot.",
};

async function loadStylePrompt(
  admin: ReturnType<typeof createClient>,
  styleKey?: string,
): Promise<string> {
  const key = styleKey || "studio_white";
  try {
    const { data } = await admin
      .from("ai_image_style_presets")
      .select("prompt")
      .eq("key", key)
      .eq("enabled", true)
      .maybeSingle();
    if (data?.prompt) return data.prompt as string;
  } catch (e) {
    console.warn("loadStylePrompt error", e);
  }
  return FALLBACK_PRESETS[key] || FALLBACK_PRESETS.studio_white;
}

function buildPrompt(
  name: string,
  description: string | undefined,
  extra: string | undefined,
  styleSnippet: string,
) {
  return [
    `Professional e-commerce product photography of "${name}".`,
    description ? `Product details: ${description}.` : "",
    styleSnippet,
    "High resolution, sharp focus, realistic materials and textures, true-to-life colors, no text, no watermark, no people, no logos.",
    extra || "",
  ].filter(Boolean).join(" ");
}

Deno.serve(async (req) => {
  const pre = handlePreflight(req);
  if (pre) return pre;

  try {
    const { name, description, extraPrompt, style } = await req.json().catch(() => ({}));
    if (!name || typeof name !== "string") return json({ error: "name 必填" }, 400);

    // 鉴权 - 仅登录用户可调用
    const authHeader = req.headers.get("Authorization") ?? "";
    const userClient = createClient(SUPABASE_URL, SERVICE_ROLE, {
      global: { headers: { Authorization: authHeader } },
    });
    const { data: userData } = await userClient.auth.getUser();
    if (!userData?.user) return json({ error: "未登录" }, 401);

    const admin = createClient(SUPABASE_URL, SERVICE_ROLE);
    const styleSnippet = await loadStylePrompt(admin, style);
    const prompt = buildPrompt(name, description, extraPrompt, styleSnippet);
    const cfg = await loadProviderConfig("product_image");
    const img = await generateImage("product_image", { prompt });

    // 上传到 storage
    const ext = (img.mime.split("/")[1] || "png").replace("jpeg", "jpg");
    const bytes = base64ToBytes(img.base64);
    const path = `products/ai_${Date.now()}_${Math.random().toString(36).slice(2, 8)}.${ext}`;
    const { error: upErr } = await admin.storage
      .from("product-images")
      .upload(path, bytes, { contentType: img.mime, upsert: false });
    if (upErr) {
      console.error("upload error", upErr);
      return json({ error: "图片上传失败" }, 500);
    }
    const { data: pub } = admin.storage.from("product-images").getPublicUrl(path);

    return json({ url: pub.publicUrl, path, provider: cfg.provider, model: cfg.model });
  } catch (e: any) {
    console.error("product-image-generate error", e);
    const status = e?.status ?? 500;
    return json({ error: e?.message ?? String(e), code: e?.code }, status);
  }
});
