import { supabase } from "@/integrations/supabase/client";
import { normalizeStepImage } from "@/services/stepImageNormalization";

export const STEP_IMAGE_BUCKET = "step-images";
const ALLOWED = new Set(["image/jpeg", "image/png", "image/webp"]);
const MAX_BYTES = 5 * 1024 * 1024;
const SIGNED_URL_CACHE_MS = 55 * 60 * 1000;
const signedUrlCache = new Map<string, { url: string; expiresAt: number }>();
const signedUrlRequests = new Map<string, Promise<string>>();

export function validateStepImage(file: File) {
  if (!ALLOWED.has(file.type)) throw new Error("Choisissez une image JPG, PNG ou WebP.");
  if (!file.size || file.size > MAX_BYTES) throw new Error("L’image doit peser moins de 5 Mo.");
}

export function buildStepImagePath(tripId: string, stepId: string, file: File) {
  validateStepImage(file);
  const extension = file.type === "image/png" ? "png" : file.type === "image/webp" ? "webp" : "jpg";
  return `${tripId}/${stepId}/${crypto.randomUUID()}.${extension}`;
}

export async function uploadStepImage(tripId: string, stepId: string, file: File, onPhase?: (phase: "preparing" | "uploading") => void) {
  validateStepImage(file);
  onPhase?.("preparing");
  const normalizedFile = await normalizeStepImage(file);
  const path = buildStepImagePath(tripId, stepId, normalizedFile);
  onPhase?.("uploading");
  const { error } = await supabase.storage.from(STEP_IMAGE_BUCKET).upload(path, normalizedFile, { cacheControl: "3600", upsert: false, contentType: normalizedFile.type });
  if (error) throw error;
  return path;
}

export async function removeStepImage(path: string) {
  const { error } = await supabase.storage.from(STEP_IMAGE_BUCKET).remove([path]);
  if (error) throw error;
  signedUrlCache.delete(path);
  signedUrlRequests.delete(path);
}

export function getCachedStepImageUrl(path?: string | null) {
  if (!path) return null;
  const cached = signedUrlCache.get(path);
  if (!cached || cached.expiresAt <= Date.now()) { signedUrlCache.delete(path); return null; }
  return cached.url;
}

export function getStepImageUrl(path: string) {
  const cached = getCachedStepImageUrl(path);
  if (cached) return Promise.resolve(cached);
  const pending = signedUrlRequests.get(path);
  if (pending) return pending;
  const request = supabase.storage.from(STEP_IMAGE_BUCKET).createSignedUrl(path, 3600).then(({ data, error }) => {
    if (error) throw error;
    signedUrlCache.set(path, { url: data.signedUrl, expiresAt: Date.now() + SIGNED_URL_CACHE_MS });
    return data.signedUrl;
  }).finally(() => signedUrlRequests.delete(path));
  signedUrlRequests.set(path, request);
  return request;
}
