const crypto=require("crypto"),{Op}=require("sequelize"),db=require("../../models"),loyalty=require("./loyalty.service");async function birthdays(limit=100){const today=new Date(),profiles=await db.Profile.findAll({where:{dob:{[Op.ne]:null}},limit});let count=0;for(const profile of profiles){const dob=new Date(profile.dob);if(dob.getUTCMonth()!==today.getUTCMonth()||dob.getUTCDate()!==today.getUTCDate())continue;const rule=await db.LoyaltyEarnRule.findOne({where:{source_type:"BIRTHDAY",status:"ACTIVE"}});if(rule?.fixed_points){await loyalty.post({userId:profile.user_id,eventId:`LOYALTY:BIRTHDAY:${profile.user_id}:${today.getUTCFullYear()}`,type:"EARN",sourceType:"BIRTHDAY",sourceId:String(today.getUTCFullYear()),points:rule.fixed_points,descriptionCode:"ANNUAL_BIRTHDAY"});count++;}}return count;}async function expire(limit=100){const allocations=await db.LoyaltyPointAllocation.findAll({where:{remaining_points:{[Op.gt]:0},expires_at:{[Op.lte]:new Date()}},limit,order:[["expires_at","ASC"]]});for(const allocation of allocations)await db.sequelize.transaction(async transaction=>{const row=await db.LoyaltyPointAllocation.findByPk(allocation.id,{transaction,lock:transaction.LOCK.UPDATE});if(!row||row.remaining_points<=0)return;const account=await db.LoyaltyAccount.findByPk(row.loyalty_account_id,{transaction});await loyalty.post({userId:account.user_id,eventId:`LOYALTY:EXPIRE:${row.id}`,type:"EXPIRE",sourceType:"POINT_EXPIRY",sourceId:row.id,points:-row.remaining_points,descriptionCode:"POINTS_EXPIRED"},transaction);await row.update({remaining_points:0},{transaction});});return allocations.length;}module.exports={birthdays,expire};