import { z } from "zod";

export const batchPromotionMemberSchema = z.object({
    member_id: z.number({ invalid_type_error: "Must select a member" }).int().positive(),
    rank_id: z.number({ invalid_type_error: "Must select a rank" }).int().positive(),
    start_date: z.string().refine((val) => !isNaN(Date.parse(val)), {
        message: "Must be a valid date",
    }),
});

export const batchPromotionSchema = z.object({
    promotions: z.array(batchPromotionMemberSchema, { message: "At least one promotion is required" }).nonempty({ message: "At least one promotion is required" }),
    approver: z.number({ invalid_type_error: "Must select a member" }).int().positive()
})
    .superRefine((data, ctx) => {
        // optional: check for duplicate member_ids
        const memberCounts = new Map<number, number>();
        data.promotions.forEach((p, index) => {
            memberCounts.set(p.member_id, (memberCounts.get(p.member_id) ?? 0) + 1);
            if (memberCounts.get(p.member_id)! > 1) {
                ctx.addIssue({
                    code: z.ZodIssueCode.custom,
                    path: ["promotions", index, "member_id"],
                    message: "Duplicate member in batch is not allowed",
                });
            }
        });
    });


export type BatchPromotion = z.infer<typeof batchPromotionSchema>;
export type BatchPromotionMember = z.infer<typeof batchPromotionMemberSchema>;