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;          // optional
  rasterFile?: File;       // optional (.png/.jpg/.jpeg)
  name: string;
  description?: string;
  tags?: string[];
  version: number;
  geometry?: CanvasGeom;
  defaults?: Record<string, string>;
  public?: boolean;
};

export type LogoTemplateDoc = {
  templateId: string;
  name: string;
  description: string;
  tags: string[];
  version: number;
  ownerId: string;
  public: boolean;
  storagePaths: { svg?: string; raster?: string };
  downloadURLs: { svg?: string; raster?: string };
  bytes: { svg?: number; raster?: number };
  formats: string[]; // ["svg"] or ["svg","png"] etc.
  geometry?: CanvasGeom;
  defaults?: Record<string, string>;
  createdAt: any;
  updatedAt: any;
};

function extFromName(name: string) {
  return (name.split(".").pop() || "").toLowerCase();
}
function contentTypeFor(file: File, fallbackExt: string) {
  if (file.type) return file.type;
  if (fallbackExt === "svg") return "image/svg+xml";
  if (fallbackExt === "png") return "image/png";
  if (fallbackExt === "jpg" || fallbackExt === "jpeg") return "image/jpeg";
  return "application/octet-stream";
}

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,
  } = input;

  if (!name?.trim()) throw new Error("Missing template name");
  if (!svgFile && !rasterFile) throw new Error("Provide at least one file: SVG or PNG/JPG");

  const userUid = user.uid;
  const templateId = buildTemplateId(name, version);

  try { await getDoc(doc(db, "logo_templates", templateId)); } catch {}

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

  if (svgFile) {
    const svgPath = `templates/logos/${userUid}/${templateId}/source.svg`;
    const svgRef = ref(storage, svgPath);
    const meta: UploadMetadata = {
      contentType: contentTypeFor(svgFile, "svg"),
      customMetadata: { ownerId: userUid, templateId, name, version: String(version) },
    };
    await uploadBytes(svgRef, svgFile, meta);
    storagePaths.svg = svgPath;
    downloadURLs.svg = await getDownloadURL(svgRef);
    bytes.svg = svgFile.size;
    formats.push("svg");
  }

  if (rasterFile) {
    const ext = extFromName(rasterFile.name);
    const safeExt = ["png", "jpg", "jpeg"].includes(ext) ? (ext === "jpeg" ? "jpg" : ext) : "png";
    const rasterPath = `templates/logos/${userUid}/${templateId}/preview.${safeExt}`;
    const rasterRef = ref(storage, rasterPath);
    const meta: UploadMetadata = {
      contentType: contentTypeFor(rasterFile, safeExt),
      customMetadata: { ownerId: userUid, templateId, name, version: String(version) },
    };
    await uploadBytes(rasterRef, rasterFile, meta);
    storagePaths.raster = rasterPath;
    downloadURLs.raster = await getDownloadURL(rasterRef);
    bytes.raster = rasterFile.size;
    if (!formats.includes(safeExt)) formats.push(safeExt);
  }

  const payload: LogoTemplateDoc = {
    templateId,
    name,
    description,
    tags,
    version,
    ownerId: userUid,
    public: isPublic,
    storagePaths,
    downloadURLs,
    bytes,
    formats,
    geometry,
    defaults,
    createdAt: serverTimestamp(),
    updatedAt: serverTimestamp(),
  };

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