import type { FastifyInstance } from 'fastify';
import type { Sql } from '../db.js';

// ── Row types matching memory_entries table columns ───────────────────────
// These mirror the frontend types in apps/web/src/api/types.ts.

interface MemoryEntryRow {
  id: string;
  topic: string;
  title: string;
  content: string;
  tags: string[];
}

interface DailyMemoryEntryRow extends MemoryEntryRow {
  date: string;
}

interface DreamEntryRow {
  date: string;
  content: string;
}

export function registerMemoryRoutes(app: FastifyInstance, sql: Sql): void {
  // GET /api/memory?project_id=<id> — topic-based memory entries
  app.get<{ Querystring: { project_id?: string } }>(
    '/api/memory',
    async (req) => {
      const projectId = req.query.project_id
      if (!projectId) {
        return { entries: [] }
      }

      const rows = await sql<MemoryEntryRow[]>`
        SELECT id, topic, title, content, COALESCE(tags, ARRAY[]::text[]) AS tags
        FROM memory_entries
        WHERE project_id = ${projectId}
          AND date IS NULL
        ORDER BY created_at DESC
      `

      return { entries: rows }
    },
  )

  // GET /api/memory/daily?project_id=<id> — daily log entries
  app.get<{ Querystring: { project_id?: string } }>(
    '/api/memory/daily',
    async (req) => {
      const projectId = req.query.project_id
      if (!projectId) {
        return { entries: [] }
      }

      const rows = await sql<DailyMemoryEntryRow[]>`
        SELECT
          id, topic, title, content,
          COALESCE(tags, ARRAY[]::text[]) AS tags,
          date::text AS date
        FROM memory_entries
        WHERE project_id = ${projectId}
          AND date IS NOT NULL
          AND mood IS NULL
        ORDER BY date DESC, created_at DESC
      `

      return { entries: rows }
    },
  )

  // GET /api/memory/dreams?project_id=<id> — dream consolidation diaries
  app.get<{ Querystring: { project_id?: string } }>(
    '/api/memory/dreams',
    async (req) => {
      const projectId = req.query.project_id
      if (!projectId) {
        return { entries: [] }
      }

      const rows = await sql<DreamEntryRow[]>`
        SELECT date::text AS date, content
        FROM memory_entries
        WHERE project_id = ${projectId}
          AND mood IS NOT NULL
        ORDER BY date DESC, created_at DESC
      `

      return { entries: rows }
    },
  )
}
