import { getAdminDb } from '@/lib/firebase/admin';
import { FieldValue } from 'firebase-admin/firestore';
import type {
  KnowledgeItem,
  KnowledgeSourceMeta,
  KnowledgeSourceType,
} from '@/lib/types/knowledge';

const COLLECTION = 'knowledge_items';

interface CreateKnowledgeItemInput {
  projectId: string;
  sourceType: KnowledgeSourceType;
  title?: string | null;
  content: string;
  sourceMeta?: KnowledgeSourceMeta;
}

export async function createKnowledgeItem(
  input: CreateKnowledgeItemInput,
): Promise<KnowledgeItem> {
  const adminDb = getAdminDb();
  const docRef = adminDb.collection(COLLECTION).doc();

  const payload = {
    id: docRef.id,
    projectId: input.projectId,
    sourceType: input.sourceType,
    title: input.title ?? null,
    content: input.content,
    sourceMeta: input.sourceMeta ?? null,
    createdAt: FieldValue.serverTimestamp(),
    updatedAt: FieldValue.serverTimestamp(),
  };

  await docRef.set(payload);
  const snapshot = await docRef.get();
  return snapshot.data() as KnowledgeItem;
}

export async function getKnowledgeItem(
  projectId: string,
  knowledgeItemId: string,
): Promise<KnowledgeItem | null> {
  const adminDb = getAdminDb();
  const docRef = adminDb.collection(COLLECTION).doc(knowledgeItemId);
  const snapshot = await docRef.get();

  if (!snapshot.exists) {
    return null;
  }

  const data = snapshot.data() as KnowledgeItem;
  if (data.projectId !== projectId) {
    return null;
  }

  return data;
}

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

  return querySnapshot.docs.map((doc) => doc.data() as KnowledgeItem);
}


