import prisma from '../lib/prisma.js';

/**
 * Recalculate AgentUsage for the current calendar month from ground truth properties.
 * This is designed to be idempotent and safe to call from multiple flows.
 */
export const recalcAgentUsageForCurrentPeriod = async (userId: string, now = new Date()) => {
  const periodStart = new Date(now.getFullYear(), now.getMonth(), 1);
  const periodEnd = new Date(now.getFullYear(), now.getMonth() + 1, 1);

  // Count properties created in this month by this agent
  const listingsPostedCount = await prisma.property.count({
    where: {
      ownerId: userId,
      createdAt: { gte: periodStart, lt: periodEnd },
    },
  });

  // Count ACTIVE listings for this agent (regardless of created date)
  const activeListingsCount = await prisma.property.count({
    where: {
      ownerId: userId,
      status: 'ACTIVE',
    },
  });

  await (prisma as any).agentUsage.upsert({
    where: { userId_periodStart: { userId, periodStart } },
    update: { periodEnd, listingsPostedCount, activeListingsCount },
    create: {
      userId,
      periodStart,
      periodEnd,
      listingsPostedCount,
      activeListingsCount,
    },
  });
};
