import { Injectable } from '@nestjs/common';
import { PrismaService } from 'src/prisma/prisma.service';
import { FECHA_LANZAMIENTO, fechaFin } from './recorrido-renovacion.constantes';

@Injectable()
export class RecorridoRenovacionService {
  constructor(private readonly prisma: PrismaService) {}

  async estado(usuarioId: string, ahora: Date = new Date()): Promise<{ mostrar: boolean; vigente: boolean }> {
    // `vigente`: el período del recorrido sigue abierto (página «¿Dónde quedó…?», Ayuda y buscador); no depende del usuario.
    const vigente = ahora.getTime() < fechaFin().getTime();
    if (!vigente) return { mostrar: false, vigente };

    const usuario = await this.prisma.usuario.findUnique({
      where: { id: usuarioId },
      select: { created_at: true },
    });
    if (!usuario) return { mostrar: false, vigente };
    // created_at nulo = usuario antiguo (anterior a que existiera la columna).
    if (usuario.created_at && usuario.created_at.getTime() >= FECHA_LANZAMIENTO.getTime()) {
      return { mostrar: false, vigente };
    }

    const visto = await this.prisma.recorrido_renovacion_visto.findUnique({ where: { usuario_id: usuarioId } });
    return { mostrar: !visto, vigente };
  }

  async marcarTerminado(usuarioId: string): Promise<void> {
    await this.prisma.recorrido_renovacion_visto.upsert({
      where: { usuario_id: usuarioId },
      create: { usuario_id: usuarioId },
      update: {},
    });
  }
}
