import { writable } from "svelte/store";
import type { Doc, Id } from "@sgse-app/backend/convex/_generated/dataModel";

export type TicketDetalhe = {
  ticket: Doc<"tickets">;
  interactions: Doc<"ticketInteractions">[];
};

function createChamadosStore() {
  const tickets = writable<Array<Doc<"tickets">>>([]);
  const detalhes = writable<Record<string, TicketDetalhe>>({});
  const carregando = writable(false);

  function setTickets(lista: Array<Doc<"tickets">>) {
    tickets.set(lista);
  }

  function upsertTicket(ticket: Doc<"tickets">) {
    tickets.update((current) => {
      const existente = current.findIndex((t) => t._id === ticket._id);
      if (existente >= 0) {
        const copia = [...current];
        copia[existente] = ticket;
        return copia;
      }
      return [ticket, ...current];
    });
  }

  function setDetalhe(ticketId: Id<"tickets">, detalhe: TicketDetalhe) {
    detalhes.update((mapa) => ({
      ...mapa,
      [ticketId]: detalhe,
    }));
  }

  function setCarregando(flag: boolean) {
    carregando.set(flag);
  }

  return {
    tickets,
    detalhes,
    carregando,
    setTickets,
    upsertTicket,
    setDetalhe,
    setCarregando,
  };
}

export const chamadosStore = createChamadosStore();

