import { db } from "@/utils/firebase-templates";
import {
  collection,
  getDocs,
  limit,
  orderBy,
  query,
  startAfter,
  DocumentData,
  QueryDocumentSnapshot,
  where,
  updateDoc,
  doc,
  deleteDoc,
} from "firebase/firestore";

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[];
  geometry?: { canvas: { w: number; h: number } };
  defaults?: Record<string, string>;
  createdAt?: any;
  updatedAt?: any;
};

export type FetchResult = {
  items: (LogoTemplateDoc & { _snap: QueryDocumentSnapshot<DocumentData> })[];
  nextPageCursor?: QueryDocumentSnapshot<DocumentData>;
};

export async function fetchLogoTemplates(opts?: {
  pageSize?: number;
  cursor?: QueryDocumentSnapshot<DocumentData>;
  onlyPublic?: boolean;
  ownerId?: string;
}): Promise<FetchResult> {
  const { pageSize = 50, cursor, onlyPublic, ownerId } = opts || {};
  const col = collection(db, "logo_templates");
  const clauses = [];
  if (onlyPublic) clauses.push(where("public", "==", true));
  if (ownerId) clauses.push(where("ownerId", "==", ownerId));

  let q = query(col, ...clauses, orderBy("createdAt", "desc"), limit(pageSize));
  if (cursor) q = query(col, ...clauses, orderBy("createdAt", "desc"), startAfter(cursor), limit(pageSize));

  const snap = await getDocs(q);
  const docs = snap.docs.map(d => ({ ...(d.data() as LogoTemplateDoc), _snap: d }));
  const nextPageCursor = snap.docs.length === pageSize ? snap.docs[snap.docs.length - 1] : undefined;

  return { items: docs, nextPageCursor };
}

export async function setTemplatePublic(templateId: string, value: boolean) {
  await updateDoc(doc(db, "logo_templates", templateId), { public: value });
}

export async function deleteTemplate(templateId: string) {
  await deleteDoc(doc(db, "logo_templates", templateId));
}
