const prisma = require("./client");

async function voteDealTx({ dealId, userId, voteType }) {
  return prisma.$transaction(async (db) => {
    const current = await db.dealVote.findUnique({
      where: { dealId_userId: { dealId, userId } },
      select: { voteType: true },
    });

    const oldValue = current ? current.voteType : 0;
    const delta = voteType - oldValue;

    // history (append-only)
    await db.dealVoteHistory.create({
      data: { dealId, userId, voteType },
    });

    // current state
    await db.dealVote.upsert({
      where: { dealId_userId: { dealId, userId } },
      create: {
        dealId,
        userId,
        voteType,
        lastVotedAt: new Date(),
      },
      update: {
        voteType,
        lastVotedAt: new Date(),
      },
    });

    // score delta
    if (delta !== 0) {
      await db.deal.update({
        where: { id: dealId },
        data: { score: { increment: delta } },
      });
    }

    const deal = await db.deal.findUnique({
      where: { id: dealId },
      select: { score: true },
    });

    return {
      dealId,
      voteType,
      delta,
      score: deal?.score ?? null,
    };
  });
}

module.exports = {
  voteDealTx,
};
