// src/services/templates.ts
import { 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 = {
  adminUid: string;
  name: string;              // Display name / description
  description?: string;
  tags?: string[];
  version: number;           // e.g. 1
  svgFile: File;             // Source vector to store
  geometry?: { canvas: { w: number; h: number } };
  defaults?: Record<string, string>; // e.g. { brandName, tagline, estYear }
  public?: boolean;          // default true
};

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

export async function uploadTemplate(input: UploadTemplateInput): Promise<{ templateId: string }> {
  const {
    adminUid,
    name,
    description = name,
    tags = [],
    version,
    svgFile,
    geometry,
    defaults = {},
    public: isPublic = true,
  } = input;

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

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

  // Check if a doc already exists to avoid accidental overwrite (optional; safe to keep)
  const existing = await getDoc(doc(db, "logo_templates", templateId));
  // You can allow overwrites if same version is intentional; we’ll just proceed.

  // Storage path
  const svgPath = `templates/logos/${adminUid}/${templateId}/source.svg`;

  // Upload SVG
  const svgRef = ref(storage, svgPath);
  const meta: UploadMetadata = {
    contentType: "image/svg+xml",
    customMetadata: {
      ownerId: adminUid,
      templateId,
      name,
      version: String(version),
    },
  };
  await uploadBytes(svgRef, svgFile, meta);

  // Resolve download URL
  const svgURL = await getDownloadURL(svgRef);

  // Firestore doc
  const docRef = doc(collection(db, "logo_templates"), templateId);
  const payload: LogoTemplateDoc = {
    templateId,
    name,
    description,
    tags,
    version,
    ownerId: adminUid,
    public: isPublic,
    storagePaths: { svg: svgPath },
    downloadURLs: { svg: svgURL },
    bytes: { svg: svgFile.size },
    geometry,
    defaults,
    createdAt: serverTimestamp(),
    updatedAt: serverTimestamp(),
  };

  await setDoc(docRef, payload);
  return { templateId };
}
