// src/services/templates.ts
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";

export type UploadTemplateInput = {
  // NOTE: we will IGNORE any incoming UID and always use auth.currentUser.uid
  adminUid?: string;          // kept for backward-compat, but unused
  name: string;               // Display name
  description?: string;
  tags?: string[];
  version: number;            // e.g., 1
  svgFile: File;              // Source vector
  geometry?: { canvas: { w: number; h: number } };
  defaults?: Record<string, string>;
  public?: boolean;           // default true
};

export type LogoTemplateDoc = {
  templateId: string;
  name: string;
  description: string;
  tags: string[];
  version: number;
  ownerId: string;            // MUST equal auth.uid per rules
  public: boolean;
  storagePaths: { svg: string };
  downloadURLs: { svg: string };
  bytes: { svg: number };
  geometry?: { canvas: { w: number; h: number } };
  defaults?: Record<string, string>;
  createdAt: any;
  updatedAt: any;
};

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

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

  if (!name?.trim()) throw new Error("Missing template name");
  if (!svgFile) throw new Error("Missing SVG file");

  // Deterministic ID, e.g. "scales-of-justice-v1"
  const templateId = buildTemplateId(name, version);

  // (Optional) Check if exists
  try {
    const maybe = await getDoc(doc(db, "logo_templates", templateId));
    // you can decide to block duplicates here if desired
    // if (maybe.exists()) throw new Error("Template ID already exists");
  } catch (e) {
    console.warn("[uploadTemplate] getDoc precheck warning:", e);
  }

  // --- STORAGE UPLOAD ---
  const svgPath = `templates/logos/${userUid}/${templateId}/source.svg`;
  const svgRef = ref(storage, svgPath);

  const meta: UploadMetadata = {
    contentType: "image/svg+xml",
    customMetadata: {
      ownerId: userUid,
      templateId,
      name,
      version: String(version),
    },
  };

  try {
    await uploadBytes(svgRef, svgFile, meta);
  } catch (e: any) {
    console.error("[uploadTemplate] Storage upload failed:", e?.code, e?.message || e);
    throw e;
  }

  let svgURL: string;
  try {
    svgURL = await getDownloadURL(svgRef);
  } catch (e: any) {
    console.error("[uploadTemplate] getDownloadURL failed:", e?.code, e?.message || e);
    throw e;
  }

  // --- FIRESTORE WRITE ---
  const docRef = doc(collection(db, "logo_templates"), templateId);
  const payload: LogoTemplateDoc = {
    templateId,
    name,
    description,
    tags,
    version,
    ownerId: userUid,             // CRITICAL: must match auth.uid
    public: isPublic,
    storagePaths: { svg: svgPath },
    downloadURLs: { svg: svgURL },
    bytes: { svg: svgFile.size },
    geometry,
    defaults,
    createdAt: serverTimestamp(),
    updatedAt: serverTimestamp(),
  };

  try {
    await setDoc(docRef, payload);
  } catch (e: any) {
    console.error("[uploadTemplate] Firestore write failed:", e?.code, e?.message || e);
    throw e;
  }

  return { templateId };
}
