/**
 * Integration tests for Analytics endpoints.
 * Uses a real Postgres test DB and Redis test instance.
 *
 * Routes covered:
 *   GET /api/v1/analytics/tokens          — daily token issuance trend
 *   GET /api/v1/analytics/agents/activity — agent activity heatmap
 *   GET /api/v1/analytics/agents          — per-agent usage summary
 */

import crypto from 'crypto';
import request from 'supertest';
import { Application } from 'express';
import { v4 as uuidv4 } from 'uuid';
import { Pool } from 'pg';

const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
  modulusLength: 2048,
  publicKeyEncoding: { type: 'spki', format: 'pem' },
  privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
});

process.env['DATABASE_URL'] =
  process.env['TEST_DATABASE_URL'] ??
  'postgresql://sentryagent:sentryagent@localhost:5432/sentryagent_idp_test';
process.env['REDIS_URL'] = process.env['TEST_REDIS_URL'] ?? 'redis://localhost:6379/1';
process.env['JWT_PRIVATE_KEY'] = privateKey;
process.env['JWT_PUBLIC_KEY'] = publicKey;
process.env['NODE_ENV'] = 'test';
process.env['DEFAULT_ORG_ID'] = 'org_system';
process.env['ANALYTICS_ENABLED'] = 'true';

import { createApp } from '../../src/app';
import { signToken } from '../../src/utils/jwt';
import { closePool } from '../../src/db/pool';
import { closeRedisClient } from '../../src/cache/redis';

const ORG_ID = uuidv4();
const AGENT_ID = uuidv4();
const SCOPE = 'analytics:read';

function makeToken(sub: string = AGENT_ID, scope: string = SCOPE, orgId: string = ORG_ID): string {
  return signToken({ sub, client_id: sub, scope, organization_id: orgId, jti: uuidv4() }, privateKey);
}

describe('Analytics Endpoints Integration Tests', () => {
  let app: Application;
  let pool: Pool;

  beforeAll(async () => {
    app = await createApp();
    pool = new Pool({ connectionString: process.env['DATABASE_URL'] });

    await pool.query(`
      CREATE TABLE IF NOT EXISTS organizations (
        organization_id VARCHAR(40) PRIMARY KEY,
        name VARCHAR(100) NOT NULL,
        plan VARCHAR(20) NOT NULL DEFAULT 'free',
        created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
        updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
      )
    `);

    await pool.query(`
      CREATE TABLE IF NOT EXISTS analytics_events (
        id BIGSERIAL PRIMARY KEY,
        tenant_id VARCHAR(40) NOT NULL,
        date DATE NOT NULL,
        metric_type VARCHAR(50) NOT NULL,
        count INTEGER NOT NULL DEFAULT 1,
        UNIQUE(tenant_id, date, metric_type)
      )
    `);

    await pool.query(
      `INSERT INTO organizations (organization_id, name) VALUES ($1, $2) ON CONFLICT DO NOTHING`,
      [ORG_ID, 'Test Analytics Org'],
    );
  });

  afterAll(async () => {
    await pool.query(`DELETE FROM analytics_events WHERE tenant_id = $1`, [ORG_ID]);
    await pool.query(`DELETE FROM organizations WHERE organization_id = $1`, [ORG_ID]);
    await pool.end();
    await closePool();
    await closeRedisClient();
  });

  // ─── GET /analytics/tokens ──────────────────────────────────────────────────

  describe('GET /api/v1/analytics/tokens', () => {
    it('should return 200 with token trend data', async () => {
      const res = await request(app)
        .get('/api/v1/analytics/tokens')
        .set('Authorization', `Bearer ${makeToken()}`);

      expect(res.status).toBe(200);
      expect(Array.isArray(res.body)).toBe(true);
    });

    it('should return 401 when no token provided', async () => {
      const res = await request(app).get('/api/v1/analytics/tokens');
      expect(res.status).toBe(401);
    });

    it('should accept a ?days= query parameter', async () => {
      const res = await request(app)
        .get('/api/v1/analytics/tokens?days=7')
        .set('Authorization', `Bearer ${makeToken()}`);

      expect(res.status).toBe(200);
    });
  });

  // ─── GET /analytics/agents/activity ─────────────────────────────────────────

  describe('GET /api/v1/analytics/agents/activity', () => {
    it('should return 200 with activity data', async () => {
      const res = await request(app)
        .get('/api/v1/analytics/agents/activity')
        .set('Authorization', `Bearer ${makeToken()}`);

      expect(res.status).toBe(200);
    });

    it('should return 401 when no token provided', async () => {
      const res = await request(app).get('/api/v1/analytics/agents/activity');
      expect(res.status).toBe(401);
    });
  });

  // ─── GET /analytics/agents ───────────────────────────────────────────────────

  describe('GET /api/v1/analytics/agents', () => {
    it('should return 200 with agent usage summary', async () => {
      const res = await request(app)
        .get('/api/v1/analytics/agents')
        .set('Authorization', `Bearer ${makeToken()}`);

      expect(res.status).toBe(200);
    });

    it('should return 401 when no token provided', async () => {
      const res = await request(app).get('/api/v1/analytics/agents');
      expect(res.status).toBe(401);
    });
  });
});
