/**
 * Memora adapter — uses BackendAdapter for database access.
 * Replaces the Tauri-coupled MemoraAdapter from memora-bridge.ts.
 */

import { getBackend } from '../backend/backend';
import type { MemoryAdapter, MemoryNode, MemorySearchResult } from './memory-adapter';

function toMemoryNode(n: { id: number; content: string; tags: string[]; metadata?: Record<string, unknown>; created_at?: string; updated_at?: string }): MemoryNode {
  return {
    id: n.id,
    content: n.content,
    tags: n.tags,
    metadata: n.metadata,
    created_at: n.created_at,
    updated_at: n.updated_at,
  };
}

export class MemoraAdapter implements MemoryAdapter {
  readonly name = 'memora';
  private _available: boolean | null = null;

  get available(): boolean {
    return this._available ?? true;
  }

  async checkAvailability(): Promise<boolean> {
    this._available = await getBackend().memoraAvailable();
    return this._available;
  }

  async list(options?: {
    tags?: string[];
    limit?: number;
    offset?: number;
  }): Promise<MemorySearchResult> {
    const result = await getBackend().memoraList(options);
    this._available = true;
    return { nodes: result.nodes.map(toMemoryNode), total: result.total };
  }

  async search(
    query: string,
    options?: { tags?: string[]; limit?: number },
  ): Promise<MemorySearchResult> {
    const result = await getBackend().memoraSearch(query, options);
    this._available = true;
    return { nodes: result.nodes.map(toMemoryNode), total: result.total };
  }

  async get(id: string | number): Promise<MemoryNode | null> {
    const numId = typeof id === 'string' ? parseInt(id, 10) : id;
    if (isNaN(numId)) return null;
    const node = await getBackend().memoraGet(numId);
    if (node) {
      this._available = true;
      return toMemoryNode(node);
    }
    return null;
  }
}
