import { auth, db, storage } from "@/utils/firebase-templates";
import { doc, setDoc, serverTimestamp, collection, getDoc } from "firebase/firestore";
import { ref, uploadBytes, getDownloadURL, UploadMetadata } from "firebase/storage";
import { buildTemplateId } from "@/utils/slugify";

type CanvasGeom = { canvas: { w: number; h: number } };

export type UploadTemplateInput = {
  svgFile?: File;
  rasterFile?: File; // png/jpg
  name: string;
  description?: string;
  tags?: string[];
  version: number;
  geometry?: CanvasGeom;
  defaults?: Record<string, string>;
  public?: boolean;   // default true
  status?: "active" | "archived";
};

export async function uploadTemplate(input: UploadTemplateInput): Promise<{ templateId: string }> {
  const user = auth.currentUser;
  if (!user) throw new Error("Not signed in");

  const {
    name, description = name, tags = [], version,
    svgFile, rasterFile, geometry, defaults = {},
    public: isPublic = true, status = "active",
  } = input;

  if (!name?.trim()) throw new Error("Missing template name");
  if (!svgFile && !rasterFile) throw new Error("Provide at least one file");

  const ownerId = user.uid;
  const templateId = buildTemplateId(name, version); // human-readable key

  // prevent accidental overwrite
  const exists = await getDoc(doc(db, "templates", templateId));
  if (exists.exists()) throw new Error(`Template "${templateId}" already exists. Bump version or rename.`);

  // upload assets
  const storagePaths: { svg?: string; raster?: string } = {};
  const downloadURLs: { svg?: string; raster?: string } = {};
  const bytes: { svg?: number; raster?: number } = {};
  const formats: string[] = [];

  if (svgFile) {
    const path = `templates/logos/${ownerId}/${templateId}/source.svg`;
    const r = ref(storage, path);
    const meta: UploadMetadata = { contentType: "image/svg+xml" };
    await uploadBytes(r, svgFile, meta);
    storagePaths.svg = path;
    downloadURLs.svg = await getDownloadURL(r);
    bytes.svg = svgFile.size;
    formats.push("svg");
  }

  if (rasterFile) {
    const ext = (rasterFile.name.split(".").pop() || "png").toLowerCase();
    const safe = ext === "jpeg" ? "jpg" : ["png", "jpg"].includes(ext) ? ext : "png";
    const path = `templates/logos/${ownerId}/${templateId}/preview.${safe}`;
    const r = ref(storage, path);
    const meta: UploadMetadata = { contentType: safe === "png" ? "image/png" : "image/jpeg" };
    await uploadBytes(r, rasterFile, meta);
    storagePaths.raster = path;
    downloadURLs.raster = await getDownloadURL(r);
    bytes.raster = rasterFile.size;
    if (!formats.includes(safe)) formats.push(safe);
  }

  const payload = {
    templateId,
    name,
    description,
    tags,
    version,
    ownerId,
    public: isPublic,
    status,                     // <— you asked for this
    storagePaths,
    downloadURLs,
    bytes,
    formats,
    geometry,
    defaults,
    createdAt: serverTimestamp(),
    updatedAt: serverTimestamp(),
  };

  await setDoc(doc(collection(db, "templates"), templateId), payload);
  return { templateId };
}
