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

export const shouldShowAgentConversionPrompt = async (userId: string) => {
  const user = await prisma.user.findUnique({ where: { id: userId }, select: { role: true } });
  if (!user || user.role !== 'OWNER') {
    return { show: false, reason: 'ROLE_NOT_OWNER' as const };
  }

  const [propertyCount, activeSubscription] = await Promise.all([
    prisma.property.count({ where: { ownerId: userId } }),
    (prisma as any).agentSubscription.findFirst({
      where: {
        userId,
        status: 'ACTIVE',
      },
      select: { id: true },
    }),
  ]);

  if (activeSubscription) {
    return { show: false, reason: 'HAS_ACTIVE_SUBSCRIPTION' as const };
  }

  // Threshold: 3+ properties suggests semi-professional behaviour
  const show = propertyCount >= 3;
  return {
    show,
    reason: show ? ('THRESHOLD_REACHED' as const) : ('TOO_FEW_PROPERTIES' as const),
    propertyCount,
  };
};
