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

export function registerBaselineRoutes(app: FastifyInstance) {
  // List baselines
  app.get('/api/v1/baselines', async (req, reply) => {
    const tenantId = (req as any).tenantId;

    const result = await withTenant(tenantId, async (client) => {
      return client.query(`
        SELECT account_id, resource_type, welford_count as sample_count,
               welford_mean::numeric(12,4) as mean,
               CASE WHEN welford_count > 1
                    THEN sqrt(welford_m2 / welford_count)::numeric(12,4)
                    ELSE 0 END as stddev,
               updated_at
        FROM baselines ORDER BY account_id, resource_type
      `);
    });

    return { baselines: result.rows };
  });

  // Reset baseline for a specific resource
  app.delete('/api/v1/baselines/:accountId/:resourceType', async (req, reply) => {
    const { accountId, resourceType } = req.params as { accountId: string; resourceType: string };
    const tenantId = (req as any).tenantId;

    await withTenant(tenantId, async (client) => {
      await client.query(
        'DELETE FROM baselines WHERE account_id = $1 AND resource_type = $2',
        [accountId, resourceType],
      );
    });

    return { status: 'reset', accountId, resourceType };
  });
}
