import { Injectable } from '@nestjs/common';
import { DatabaseService } from '../database/database.service';

@Injectable()
export class SystemService {
  constructor(private readonly db: DatabaseService) {}
  async health() {
    const database = await this.db.ping();
    let cron: Record<string, unknown> = { configured: this.db.isConfigured(), status: 'UNKNOWN' };
    let backup: Record<string, unknown> = { configured: this.db.isConfigured(), status: 'UNKNOWN' };
    if (this.db.isConfigured()) {
      const [cronRow, backupRow] = await Promise.all([
        this.db.query(`SELECT status, started_at, finished_at FROM cron_runs ORDER BY started_at DESC LIMIT 1`),
        this.db.query(`SELECT status, backup_type, started_at, completed_at, verified_at, restore_tested_at FROM backup_runs ORDER BY started_at DESC LIMIT 1`)
      ]);
      cron = cronRow.rows[0] ?? { status: 'NEVER_RUN' };
      backup = backupRow.rows[0] ?? { status: 'NOT_RECORDED' };
    }
    return {
      ok: database.ok,
      app: { status: 'UP', environment: process.env.NODE_ENV || 'development', subdomain: process.env.APP_BASE_URL || null },
      database,
      cron,
      backup,
      gates: {
        liveInvestment: String(process.env.LIVE_INVESTMENT ?? 'false').toLowerCase() === 'true',
        collectFunds: String(process.env.COLLECT_FUNDS ?? 'false').toLowerCase() === 'true',
        livePayments: String(process.env.LIVE_PAYMENTS ?? 'false').toLowerCase() === 'true'
      },
      checkedAt: new Date().toISOString()
    };
  }
}
