import { Pool } from 'pg';

const pool = new Pool({
  user: process.env.DB_USER || 'llm',
  password: process.env.DB_PASSWORD || 'llm_secure_2026',
  host: process.env.DB_HOST || '192.168.178.82',
  port: parseInt(process.env.DB_PORT || '5432'),
  database: process.env.DB_NAME || 'llm_gateway',
});

export interface ThreatIntelligence {
  ip_address: string;
  threat_level: string;
  confidence_score: number;
  source: string;
  details?: any;
  cached_at: string;
}

/**
 * Query threat intelligence for an IP address
 */
export async function getThreatIntel(ip: string): Promise<ThreatIntelligence | null> {
  try {
    const result = await pool.query(
      `SELECT ip_address, threat_level, confidence_score, source, details, cached_at
       FROM threat_intel
       WHERE ip_address = $1::inet
       AND expires_at > NOW()
       LIMIT 1`,
      [ip]
    );

    return result.rows.length > 0 ? result.rows[0] : null;
  } catch (error) {
    console.error('[Threat Intel Client] Error querying threat intel:', error);
    return null;
  }
}

/**
 * Check if an IP is malicious
 */
export async function isMaliciousIp(ip: string): Promise<boolean> {
  try {
    const result = await pool.query(
      `SELECT 1 FROM threat_intel
       WHERE ip_address = $1::inet
       AND threat_level IN ('CRITICAL', 'HIGH')
       AND expires_at > NOW()
       LIMIT 1`,
      [ip]
    );
    return result.rows.length > 0;
  } catch (error) {
    console.error('[Threat Intel Client] Error checking malicious IP:', error);
    return false;
  }
}

/**
 * Get threat statistics
 */
export async function getThreatStats() {
  try {
    const result = await pool.query(`
      SELECT
        COUNT(*) as total_entries,
        COUNT(CASE WHEN threat_level = 'CRITICAL' THEN 1 END) as critical_count,
        COUNT(CASE WHEN threat_level = 'HIGH' THEN 1 END) as high_count,
        COUNT(DISTINCT source) as source_count
      FROM threat_intel
      WHERE expires_at > NOW()
    `);
    return result.rows[0] || null;
  } catch (error) {
    console.error('[Threat Intel Client] Error querying stats:', error);
    return null;
  }
}

/**
 * Get threats by severity level
 */
export async function getThreatsByLevel(level: string) {
  try {
    const result = await pool.query(
      `SELECT ip_address, threat_level, confidence_score, source
       FROM threat_intel
       WHERE threat_level = $1
       AND expires_at > NOW()
       ORDER BY confidence_score DESC
       LIMIT 100`,
      [level]
    );
    return result.rows;
  } catch (error) {
    console.error('[Threat Intel Client] Error querying by level:', error);
    return [];
  }
}

export async function cleanup() {
  await pool.end();
}
