import { query } from '@/lib/db-postgres';
import { randomUUID } from 'crypto';
import type {
  KnowledgeItem,
  KnowledgeSourceMeta,
  KnowledgeSourceType,
} from '@/lib/types/knowledge';

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

function rowToItem(row: { id: string; project_id: string; data: any; created_at: string; updated_at: string }): KnowledgeItem {
  const d = row.data ?? {};
  return {
    id: row.id,
    projectId: row.project_id,
    sourceType: d.sourceType,
    title: d.title ?? null,
    content: d.content,
    sourceMeta: d.sourceMeta ?? null,
    createdAt: row.created_at,
    updatedAt: row.updated_at,
  } as KnowledgeItem;
}

export async function createKnowledgeItem(
  input: CreateKnowledgeItemInput,
): Promise<KnowledgeItem> {
  const id = randomUUID();
  const data = {
    sourceType: input.sourceType,
    title: input.title ?? null,
    content: input.content,
    sourceMeta: input.sourceMeta ?? null,
  };

  await query(
    `INSERT INTO fs_knowledge_items (id, project_id, data) VALUES ($1, $2, $3::jsonb)`,
    [id, input.projectId, JSON.stringify(data)]
  );

  const rows = await query<any>(
    `SELECT id, project_id, data, created_at, updated_at FROM fs_knowledge_items WHERE id = $1`,
    [id]
  );

  return rowToItem(rows[0]);
}

export async function getKnowledgeItem(
  projectId: string,
  knowledgeItemId: string,
): Promise<KnowledgeItem | null> {
  const rows = await query<any>(
    `SELECT id, project_id, data, created_at, updated_at FROM fs_knowledge_items WHERE id = $1 AND project_id = $2`,
    [knowledgeItemId, projectId]
  );
  if (rows.length === 0) return null;
  return rowToItem(rows[0]);
}

export async function listKnowledgeItems(
  projectId: string,
): Promise<KnowledgeItem[]> {
  const rows = await query<any>(
    `SELECT id, project_id, data, created_at, updated_at FROM fs_knowledge_items WHERE project_id = $1 ORDER BY created_at DESC`,
    [projectId]
  );
  return rows.map(rowToItem);
}
