/**
 * Database Routes
 *
 * Database management endpoints.
 */

import { Hono } from 'hono';
import type { AppContext } from '../router.js';
import type { DbStats, DbInitResponse } from '../types.js';

export const dbRoutes = new Hono<AppContext>();

/**
 * POST /db/init - Initialize database schema
 */
dbRoutes.post('/init', async (c) => {
  const conn = c.get('conn');

  if (!conn) {
    return c.json<DbInitResponse>(
      { success: false, message: 'No database connection' },
      500
    );
  }

  try {
    await conn.initializeSchema();

    const info = await conn.getDatabaseInfo();
    const stats: DbStats = {
      nodeCount: Object.values(info.nodeCount).reduce((a, b) => a + b, 0),
      relationshipCount: Object.values(info.relCount).reduce((a, b) => a + b, 0),
      fileCount: info.nodeCount.File ?? 0,
      functionCount: info.nodeCount.Function ?? 0,
      classCount: info.nodeCount.Class ?? 0,
      moduleCount: info.nodeCount.Module ?? 0,
    };

    return c.json<DbInitResponse>({
      success: true,
      message: 'Schema initialized',
      stats,
    });
  } catch (error) {
    return c.json<DbInitResponse>(
      {
        success: false,
        message: error instanceof Error ? error.message : 'Unknown error',
      },
      500
    );
  }
});

/**
 * POST /db/clear - Clear all data
 */
dbRoutes.post('/clear', async (c) => {
  const conn = c.get('conn');
  const { confirm } = await c.req.json<{ confirm?: boolean }>();

  if (!confirm) {
    return c.json<DbInitResponse>(
      { success: false, message: 'Confirmation required (set confirm: true)' },
      400
    );
  }

  if (!conn) {
    return c.json<DbInitResponse>(
      { success: false, message: 'No database connection' },
      500
    );
  }

  try {
    // Delete all relationships first, then nodes
    await conn.execute('MATCH ()-[r]->() DELETE r');
    await conn.execute('MATCH (n) DELETE n');

    return c.json<DbInitResponse>({
      success: true,
      message: 'All data cleared',
      stats: {
        nodeCount: 0,
        relationshipCount: 0,
        fileCount: 0,
        functionCount: 0,
        classCount: 0,
        moduleCount: 0,
      },
    });
  } catch (error) {
    return c.json<DbInitResponse>(
      {
        success: false,
        message: error instanceof Error ? error.message : 'Unknown error',
      },
      500
    );
  }
});

/**
 * GET /db/stats - Get database statistics
 */
dbRoutes.get('/stats', async (c) => {
  const conn = c.get('conn');

  if (!conn) {
    return c.json({ error: 'No database connection' }, 500);
  }

  try {
    const info = await conn.getDatabaseInfo();

    const stats: DbStats = {
      nodeCount: Object.values(info.nodeCount).reduce((a, b) => a + b, 0),
      relationshipCount: Object.values(info.relCount).reduce((a, b) => a + b, 0),
      fileCount: info.nodeCount.File ?? 0,
      functionCount: info.nodeCount.Function ?? 0,
      classCount: info.nodeCount.Class ?? 0,
      moduleCount: info.nodeCount.Module ?? 0,
    };

    return c.json(stats);
  } catch (error) {
    return c.json(
      { error: error instanceof Error ? error.message : 'Unknown error' },
      500
    );
  }
});

/**
 * GET /db/test - Test database connection
 */
dbRoutes.get('/test', async (c) => {
  const conn = c.get('conn');

  if (!conn) {
    return c.json({ connected: false, error: 'No database connection' }, 500);
  }

  try {
    const result = await conn.query('RETURN 1 AS test');
    const row = result.single();

    return c.json({
      connected: true,
      test: row?.test === 1,
    });
  } catch (error) {
    return c.json(
      {
        connected: false,
        error: error instanceof Error ? error.message : 'Unknown error',
      },
      500
    );
  }
});
