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

export type LogoTemplateDoc = {
  templateId: string;
  name: string;
  description: string;
  tags: string[];
  version: number;
  ownerId: string;
  public: boolean;
  status?: "active" | "archived";
  storagePaths: { svg?: string; raster?: string };
  downloadURLs: { svg?: string; raster?: string };
  bytes: { svg?: number; raster?: number };
  formats: string[];
  createdAt?: any;
  updatedAt?: any;
};

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

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

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

  let snap = await getDocs(q);
  if (snap.empty) {
    let q2 = query(col, ...clauses, orderBy("createdAt", "desc"), limit(pageSize));
    if (cursor) q2 = query(col, ...clauses, orderBy("createdAt", "desc"), startAfter(cursor), limit(pageSize));
    snap = await getDocs(q2);
  }

  const items = 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, nextPageCursor };
}

export async function fetchLogoTemplates(opts?: {
  pageSize?: number;
  cursor?: QueryDocumentSnapshot<DocumentData>;
  onlyPublic?: boolean;
  status?: "active" | "archived";
}): Promise<FetchResult> {
  // Try new name first
  try {
    const r = await fetchFrom("templates", opts);
    if (r.items.length) return r;
  } catch (_) {}
  // Fallback to legacy collection
  return fetchFrom("logo_templates", opts);
}
