import { Injectable, Logger } from '@nestjs/common';
import { PrismaService } from 'src/prisma/prisma.service';
import { AlertsService } from '../alerts/alerts.service';
import { InsightsService } from '../insights/insights.service';
import { TimelineService } from '../timeline/timeline.service';

@Injectable()
export class RecalculoService {
  private readonly logger = new Logger(RecalculoService.name);

  constructor(
    private readonly prisma: PrismaService,
    private readonly insights: InsightsService,
    private readonly alerts: AlertsService,
    private readonly timeline: TimelineService,
  ) {}

  /**
   * Ejecuta el recálculo completo para una empresa.
   * Llamado por el cron job nocturno o manualmente vía endpoint.
   */
  async ejecutar(empresaId: string): Promise<{ ok: boolean; detalle: string }> {
    this.logger.log(`Iniciando recálculo IA para empresa ${empresaId}`);

    const periodo = this.periodoActual();
    const errores: string[] = [];

    // 1. Insights narrativos
    try {
      await this.insights.generarInsightConIA(empresaId, periodo);
    } catch (e) {
      const msg = `Error generando insight: ${e.message}`;
      this.logger.error(msg);
      errores.push(msg);
    }

    // 2. Alertas
    try {
      await this.alerts.detectarYGuardarAlertas(empresaId);
    } catch (e) {
      const msg = `Error detectando alertas: ${e.message}`;
      this.logger.error(msg);
      errores.push(msg);
    }

    // 3. Timeline
    try {
      await this.timeline.generarEventosAutomaticos(empresaId);
    } catch (e) {
      const msg = `Error generando timeline: ${e.message}`;
      this.logger.error(msg);
      errores.push(msg);
    }

    // Actualizar timestamp último recálculo
    await this.prisma.ai_empresa_config.updateMany({
      where: { empresa_id: empresaId },
      data: { ultimo_recalculo: new Date() },
    });

    const ok = errores.length === 0;
    const detalle = ok
      ? `Recálculo completado para período ${periodo}`
      : `Completado con ${errores.length} error(es): ${errores.join(' | ')}`;

    this.logger.log(`Recálculo finalizado empresa ${empresaId} — ${detalle}`);
    return { ok, detalle };
  }

  /**
   * Ejecuta el recálculo para todas las empresas con IA activa.
   * Llamado por el cron scheduler.
   */
  async ejecutarTodas(): Promise<void> {
    const configs = await this.prisma.ai_empresa_config.findMany({
      where: { activo: true },
      select: { empresa_id: true },
    });

    this.logger.log(`Cron recálculo: ${configs.length} empresa(s) activa(s)`);

    for (const c of configs) {
      try {
        await this.ejecutar(c.empresa_id);
      } catch (e) {
        this.logger.error(`Error en recálculo empresa ${c.empresa_id}`, e);
      }
    }
  }

  private periodoActual(): string {
    const now = new Date();
    const y = now.getFullYear();
    const m = String(now.getMonth() + 1).padStart(2, '0');
    return `${y}-${m}`;
  }
}
