import { Injectable, Logger } from '@nestjs/common';
import { Cron } from '@nestjs/schedule';
import { PrismaService } from 'src/prisma/prisma.service';

/** Plan §3: mensajes y trazas 12 meses; los tickets quedan para las métricas, sin texto. */
export const MESES_RETENCION = 12;
/** Las capturas del cliente muestran pantallas enteras de su empresa: se guardan menos (§6.10). */
export const DIAS_RETENCION_CAPTURAS = 90;

/**
 * Purga mensual (día 1, 03:30). Borra el texto de las conversaciones viejas y
 * las trazas, que contienen los mismos datos del cliente. Los tickets se
 * conservan sin texto: el título (que es la primera frase del cliente) pasa a
 * ser el número, y se vacía el estado de la máquina.
 */
@Injectable()
export class RetencionCron {
  private readonly logger = new Logger(RetencionCron.name);

  constructor(private readonly prisma: PrismaService) {}

  /** Diaria (03:45): capturas de más de DIAS_RETENCION_CAPTURAS días. La lectura en texto queda con el mensaje. */
  @Cron('45 3 * * *')
  async purgarCapturas() {
    const limite = new Date(Date.now() - DIAS_RETENCION_CAPTURAS * 86_400_000);
    const { count } = await this.prisma.adjuntos.deleteMany({ where: { created_at: { lt: limite } } });
    if (count) this.logger.log(`Retención de capturas (${DIAS_RETENCION_CAPTURAS} días): ${count} borradas`);
  }

  @Cron('30 3 1 * *')
  async purgar() {
    const limite = new Date();
    limite.setMonth(limite.getMonth() - MESES_RETENCION);

    const [trazas, mensajes, tickets] = await this.prisma.$transaction([
      this.prisma.trazas.deleteMany({ where: { created_at: { lt: limite } } }),
      this.prisma.mensajes.deleteMany({ where: { created_at: { lt: limite } } }),
      this.prisma.$executeRaw`
        UPDATE tickets
           SET titulo = 'SOP-' || numero, estado_bot = '{}'::jsonb, usuario_nombre = NULL
         WHERE created_at < ${limite} AND titulo <> 'SOP-' || numero`,
    ]);
    this.logger.log(
      `Retención (${MESES_RETENCION} meses): ${trazas.count} trazas, ${mensajes.count} mensajes y ${tickets} tickets sin texto`,
    );
  }
}
