// Funções comuns da central: cadastro único de contatos, métricas diárias e "a quem pertence" cada item.
import type { Core } from '@strapi/strapi';

const hoje = () => new Date().toISOString().slice(0, 10);
export const texto = (v: unknown, max = 255) => String(v ?? '').replace(/[\u0000-\u001f\u007f]/g, ' ').trim().slice(0, max);
export const emailValido = (v: string) => /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(v);
export function normalizarWhats(v: unknown) {
  let d = String(v ?? '').replace(/\D/g, '');
  if (d.length === 10 || d.length === 11) d = '55' + d;
  return d.length >= 12 && d.length <= 13 ? d : '';
}

// Limite simples por IP (memória do processo): evita robôs enchendo o banco
const janelas = new Map<string, { n: number; ate: number }>();
export function dentroDoLimite(ip: string, chave: string, max: number, ms = 3600_000) {
  const k = `${chave}:${ip}`, agora = Date.now(), j = janelas.get(k);
  if (!j || j.ate < agora) { janelas.set(k, { n: 1, ate: agora + ms }); return true; }
  j.n++; return j.n <= max;
}

// Descobre o que é o "alvo" de um clique (estabelecimento, evento, campanha, destino) e de qual cliente ele é
type Alvo = { tipo: string; nome: string; clienteId: number | null };
const cache = new Map<string, { v: Alvo; ate: number }>();
const TIPOS: [string, string, string][] = [
  ['estabelecimento', 'api::estabelecimento.estabelecimento', 'nome'],
  ['evento', 'api::evento.evento', 'titulo'],
  ['campanha', 'api::campanha.campanha', 'anunciante'],
  ['destino', 'api::destino.destino', 'nome'],
  ['reportagem', 'api::reportagem.reportagem', 'titulo'],
];
export async function resolverAlvo(strapi: Core.Strapi, alvoBruto: string): Promise<Alvo> {
  const slug = alvoBruto.split('@')[0];
  if (!slug) return { tipo: 'pagina', nome: '', clienteId: null };
  const c = cache.get(slug); if (c && c.ate > Date.now()) return c.v;
  let v: Alvo = { tipo: 'outro', nome: slug, clienteId: null };
  for (const [tipo, uid, campoNome] of TIPOS) {
    const temCliente = ['estabelecimento', 'evento', 'campanha'].includes(tipo);
    const r: any = await strapi.db.query(uid as any).findOne({ where: { slug, publishedAt: { $notNull: true } }, populate: temCliente ? ['cliente'] : [] });
    if (r) { v = { tipo, nome: r[campoNome] || slug, clienteId: r.cliente?.id ?? null }; break; }
  }
  cache.set(slug, { v, ate: Date.now() + 5 * 60_000 });
  return v;
}

// Soma +1 na métrica do dia (ação + alvo). Uma linha por dia/ação/alvo mantém o banco pequeno.
export async function contar(strapi: Core.Strapi, acao: string, alvo: string, identificado = false) {
  const a = await resolverAlvo(strapi, alvo);
  const q = strapi.db.query('api::metrica.metrica' as any);
  const chave = alvo.split('@')[0];
  const atual: any = await q.findOne({ where: { data: hoje(), acao, alvo: chave } });
  if (atual) {
    await q.update({ where: { id: atual.id }, data: { total: (atual.total || 0) + 1, identificados: (atual.identificados || 0) + (identificado ? 1 : 0) } });
  } else {
    await strapi.documents('api::metrica.metrica' as any).create({ data: { data: hoje(), acao, alvo: chave, alvo_tipo: a.tipo, total: 1, identificados: identificado ? 1 : 0, ...(a.clienteId ? { cliente: { connect: [{ id: a.clienteId }] } } : {}) } as any });
  }
  return a;
}

// Cria ou atualiza o cadastro único (chave: e-mail). Campo vazio nunca apaga um preenchido.
export async function salvarContato(strapi: Core.Strapi, d: { email: string; nome?: string; whatsapp?: string; news?: boolean; origem?: string }) {
  const email = d.email.toLowerCase().trim();
  const agora = new Date().toISOString();
  const q = strapi.db.query('api::contato.contato' as any);
  const atual: any = await q.findOne({ where: { email } });
  if (atual) {
    await q.update({ where: { id: atual.id }, data: { nome: d.nome || atual.nome, whatsapp: d.whatsapp || atual.whatsapp, consentimento_news: !!(d.news || atual.consentimento_news), ultimo_em: agora } });
    return atual.id as number;
  }
  const novo: any = await strapi.documents('api::contato.contato' as any).create({ data: { email, nome: d.nome || '', whatsapp: d.whatsapp || '', consentimento_news: !!d.news, origem: d.origem || '', total_interacoes: 0, primeiro_em: agora, ultimo_em: agora } as any });
  return novo.id as number;
}

export async function registrarInteracao(strapi: Core.Strapi, contatoId: number, tipo: string, alvo: string, alvoNome: string, pagina: string, alvoInfo?: { tipo: string; clienteId: number | null }) {
  await strapi.documents('api::interacao.interacao' as any).create({ data: {
    contato: { connect: [{ id: contatoId }] }, tipo, alvo: alvo.split('@')[0], alvo_tipo: alvoInfo?.tipo || '', alvo_nome: alvoNome, pagina,
    ...(alvoInfo?.clienteId ? { cliente: { connect: [{ id: alvoInfo.clienteId }] } } : {}),
  } as any });
  const q = strapi.db.query('api::contato.contato' as any);
  const c: any = await q.findOne({ where: { id: contatoId } });
  if (c) await q.update({ where: { id: contatoId }, data: { total_interacoes: (c.total_interacoes || 0) + 1, ultimo_em: new Date().toISOString() } });
}
