const { z } = require("zod");

const VoteBodySchema = z.object({
  dealId: z.coerce.number().int().positive(),
  voteType: z.coerce
    .number()
    .int()
    .refine((v) => v === 1 || v === 0 || v === -1, {
      message: "voteType 1, 0 veya -1 olmalı",
    }),
});

function mapVoteRequestToVoteInput(req) {
  const parsed = VoteBodySchema.safeParse(req.body);
  if (!parsed.success) {
    const err = new Error(parsed.error.issues?.[0]?.message || "Geçersiz istek");
    err.statusCode = 400;
    err.details = parsed.error.flatten();
    throw err;
  }

  const userIdRaw = req.user?.userId;
  const userId = Number(userIdRaw);

  return {
    userId,
    dealId: parsed.data.dealId,
    voteType: parsed.data.voteType, // 1 | 0 | -1
  };
}

module.exports = { mapVoteRequestToVoteInput, VoteBodySchema };
