import { and, asc, desc, eq } from 'drizzle-orm';
import { db } from './index';
import {
  leads,
  leadFotos,
  leadNotas,
  leadEstadoHistory,
  leadPipelineEventos,
  precisionHistory,
} from './schema';
import { getCurrentTenantId as getTenantId } from '@/lib/auth/current-user';

export type LeadFiltro = (typeof leads.estado.enumValues)[number] | 'todos';

export async function getLeads(filtro: LeadFiltro = 'todos') {
  const tenantId = await getTenantId();
  const where =
    filtro === 'todos'
      ? eq(leads.tenantId, tenantId)
      : and(eq(leads.tenantId, tenantId), eq(leads.estado, filtro));

  return db.select().from(leads).where(where).orderBy(desc(leads.createdAt));
}

export async function getLead(id: string) {
  const tenantId = await getTenantId();
  const [lead] = await db
    .select()
    .from(leads)
    .where(and(eq(leads.id, id), eq(leads.tenantId, tenantId)))
    .limit(1);

  if (!lead) return null;

  const [fotos, notas, eventos, historial, precision] = await Promise.all([
    db.select().from(leadFotos).where(eq(leadFotos.leadId, id)).orderBy(asc(leadFotos.orden)),
    db.select().from(leadNotas).where(eq(leadNotas.leadId, id)).orderBy(asc(leadNotas.createdAt)),
    db
      .select()
      .from(leadPipelineEventos)
      .where(eq(leadPipelineEventos.leadId, id))
      .orderBy(asc(leadPipelineEventos.occurredAt)),
    db
      .select()
      .from(leadEstadoHistory)
      .where(eq(leadEstadoHistory.leadId, id))
      .orderBy(asc(leadEstadoHistory.changedAt)),
    db.select().from(precisionHistory).where(eq(precisionHistory.leadId, id)),
  ]);

  return { lead, fotos, notas, eventos, historial, precision: precision[0] ?? null };
}

export async function getResumen() {
  const all = await getLeads('todos');
  const porEstado = all.reduce<Record<string, number>>((acc, l) => {
    acc[l.estado] = (acc[l.estado] ?? 0) + 1;
    return acc;
  }, {});
  return { total: all.length, porEstado };
}
