import { getAdminDb } from '@/lib/firebase/admin';
import { FieldValue } from 'firebase-admin/firestore';
import type { ChatExtractionRecord } from '@/lib/types/chat-extraction';

const COLLECTION = 'chat_extractions';

interface CreateChatExtractionInput<TData> {
  projectId: string;
  knowledgeItemId: string;
  data: TData;
  overallCompletion: number;
  overallConfidence: number;
}

export async function createChatExtraction<TData>(
  input: CreateChatExtractionInput<TData>,
): Promise<ChatExtractionRecord<TData>> {
  const adminDb = getAdminDb();
  const docRef = adminDb.collection(COLLECTION).doc();

  const payload = {
    id: docRef.id,
    projectId: input.projectId,
    knowledgeItemId: input.knowledgeItemId,
    data: input.data,
    overallCompletion: input.overallCompletion,
    overallConfidence: input.overallConfidence,
    createdAt: FieldValue.serverTimestamp(),
    updatedAt: FieldValue.serverTimestamp(),
  };

  await docRef.set(payload);
  const snapshot = await docRef.get();
  return snapshot.data() as ChatExtractionRecord<TData>;
}

export async function listChatExtractions<TData>(
  projectId: string,
): Promise<ChatExtractionRecord<TData>[]> {
  const adminDb = getAdminDb();
  const querySnapshot = await adminDb
    .collection(COLLECTION)
    .where('projectId', '==', projectId)
    .orderBy('createdAt', 'desc')
    .get();

  return querySnapshot.docs.map(
    (doc) => doc.data() as ChatExtractionRecord<TData>,
  );
}

export async function getChatExtraction<TData>(
  extractionId: string,
): Promise<ChatExtractionRecord<TData> | null> {
  const adminDb = getAdminDb();
  const docRef = adminDb.collection(COLLECTION).doc(extractionId);
  const snapshot = await docRef.get();
  if (!snapshot.exists) {
    return null;
  }
  return snapshot.data() as ChatExtractionRecord<TData>;
}


