import type { Poll } from "./types.js";

/** Create a new poll document with the given title and no options */
export function createPoll(title: string): Poll {
  return {
    title,
    options: [],
  };
}

/** Add a new option to the poll */
export function addOption(poll: Poll, text: string): void {
  poll.options.push({
    id: crypto.randomUUID(),
    text,
    votes: [],
  });
}

/** Check if a peer has already voted on an option */
export function hasVoted(poll: Poll, optionId: string, peerId: string): boolean {
  const option = poll.options.find((o) => o.id === optionId);
  if (!option) return false;
  return option.votes.includes(peerId);
}

/** Add a vote for the given option. Prevents double-voting. */
export function vote(poll: Poll, optionId: string, peerId: string): void {
  const option = poll.options.find((o) => o.id === optionId);
  if (!option) return;
  if (option.votes.includes(peerId)) return;
  option.votes.push(peerId);
}

/** Remove a vote from the given option */
export function unvote(poll: Poll, optionId: string, peerId: string): void {
  const option = poll.options.find((o) => o.id === optionId);
  if (!option) return;
  const idx = option.votes.indexOf(peerId);
  if (idx !== -1) {
    option.votes.splice(idx, 1);
  }
}
