import type { FastifyInstance } from 'fastify';
import type { Sql } from '../db.js';
import type {
  SidebarProject,
  SidebarResponse,
  SidebarSession,
} from '../types/api.js';

export function registerSidebarRoutes(app: FastifyInstance, sql: Sql): void {
  app.get('/api/sidebar', async (): Promise<SidebarResponse> => {
    const projects = await sql<{ id: string; name: string; path: string; gitea_remote: string | null }[]>`
      SELECT id, name, path, gitea_remote
      FROM projects
      WHERE status = 'open'
      ORDER BY added_at DESC
    `;

    const enriched: SidebarProject[] = await Promise.all(
      projects.map(async (p) => {
        const [recent_sessions, countRows] = await Promise.all([
          sql<SidebarSession[]>`
            SELECT id, project_id, name, model, updated_at
            FROM sessions
            WHERE project_id = ${p.id} AND status = 'open'
            ORDER BY updated_at DESC
            LIMIT 6
          `,
          sql<{ n: number }[]>`
            SELECT COUNT(*)::int AS n
            FROM sessions
            WHERE project_id = ${p.id} AND status = 'open'
          `,
        ]);
        return {
          id: p.id,
          name: p.name,
          path: p.path,
          gitea_remote: p.gitea_remote,
          recent_sessions,
          total_sessions: countRows[0]?.n ?? 0,
        };
      })
    );

    return { projects: enriched };
  });
}
