export type ChatStatus = 'em_andamento' | 'concluido' | 'transferido';
export type ChatStage = 'prospeccao' | 'qualificacao' | 'apresentacao' | 'fechado';

export type ChatMeta = {
  status: ChatStatus;
  tags: string[];
  responsavel: string;
  stage: ChatStage;
};

export const RESPONSAVEIS = ['Suporte', 'Vendas', 'Gestao'];

export const STAGES: { id: ChatStage; label: string }[] = [
  { id: 'prospeccao', label: 'Prospeccao' },
  { id: 'qualificacao', label: 'Qualificacao' },
  { id: 'apresentacao', label: 'Apresentacao' },
  { id: 'fechado', label: 'Fechado' }
];

export const TAG_PRESETS = [
  'urgente',
  'alta',
  'normal',
  'aguardando_cliente',
  'aguardando_pagamento',
  'suporte',
  'vendas'
];

const META_KEY = 'zapbot_chat_meta';

export function defaultMeta(): ChatMeta {
  return {
    status: 'em_andamento',
    tags: [],
    responsavel: 'Sem setor',
    stage: 'prospeccao'
  };
}

export function loadMeta(): Record<string, ChatMeta> {
  try {
    const raw = localStorage.getItem(META_KEY);
    if (!raw) return {};
    return JSON.parse(raw);
  } catch (error) {
    return {};
  }
}

export function saveMeta(meta: Record<string, ChatMeta>) {
  localStorage.setItem(META_KEY, JSON.stringify(meta));
}

function randomStage(): ChatStage {
  const index = Math.floor(Math.random() * STAGES.length);
  return STAGES[index].id;
}

export function ensureMetaForChats(
  existing: Record<string, ChatMeta>,
  chatIds: string[]
) {
  let changed = false;
  const next = { ...existing };
  chatIds.forEach((id) => {
    if (!next[id]) {
      const meta = defaultMeta();
      meta.stage = randomStage();
      next[id] = meta;
      changed = true;
    } else if (!next[id].stage) {
      next[id] = { ...next[id], stage: randomStage() };
      changed = true;
    }
  });
  return { meta: next, changed };
}

export function getAllTags(meta: Record<string, ChatMeta>) {
  const tags = new Set<string>();
  Object.values(meta).forEach(item => {
    item.tags.forEach(tag => tags.add(tag));
  });
  return Array.from(tags).sort((a, b) => a.localeCompare(b));
}
