import { initDb } from "@/lib/db";
import type { ElectionTemplateSnapshot } from "@/types";

export async function listElectionTemplates(workspaceId: string) {
  const { ElectionTemplate } = initDb();
  const templates = await ElectionTemplate.findAll({
    where: { workspaceId },
    order: [["createdAt", "DESC"]],
  });

  return templates.map((template) => ({
    id: template.id,
    name: template.name,
    snapshot: template.snapshot as ElectionTemplateSnapshot,
    createdBy: template.createdBy,
    createdAt: template.createdAt,
  }));
}

export async function getElectionTemplate(
  templateId: string,
  workspaceId: string
) {
  const { ElectionTemplate } = initDb();
  return ElectionTemplate.findOne({
    where: { id: templateId, workspaceId },
  });
}

export async function getElectionDeliveries(
  electionId: string,
  workspaceId: string
) {
  const { Election, Collector, EmailCampaignDelivery, ElectionVoterRoll } =
    initDb();
  const election = await Election.findOne({
    where: { id: electionId, workspaceId },
  });
  if (!election) return [];

  const collectors = await Collector.findAll({
    where: { electionId, type: "email_campaign" },
    attributes: ["id"],
  });
  const collectorIds = collectors.map((collector) => collector.id);
  if (collectorIds.length === 0) return [];

  const deliveries = await EmailCampaignDelivery.findAll({
    where: { collectorId: collectorIds },
    order: [["sentAt", "DESC"]],
    limit: 500,
  });

  const rollIds = deliveries.map((delivery) => delivery.voterRollId);
  const rolls = await ElectionVoterRoll.findAll({
    where: { id: rollIds },
    attributes: ["id", "voterType", "voterRefId", "hasVoted"],
  });
  const rollMap = new Map(rolls.map((roll) => [roll.id, roll]));

  return deliveries.map((delivery) => {
    const roll = rollMap.get(delivery.voterRollId);
    return {
      id: delivery.id,
      voterRollId: delivery.voterRollId,
      status: delivery.status,
      sentAt: delivery.sentAt,
      hasVoted: roll?.hasVoted ?? false,
      voterType: roll?.voterType ?? null,
    };
  });
}
