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

const HOURS = 60 * 60 * 1000;
const DEFAULT_EXPIRY_JOB_HOURS = 6;

/**
 * Periodically marks ACTIVE agent subscriptions as EXPIRED when endDate has passed.
 *
 * This job centralizes expiry handling so request handlers can mostly rely on up-to-date status,
 * while still performing defensive checks.
 */
export const startAgentSubscriptionExpiryJob = () => {
  let timer: NodeJS.Timeout | undefined;

  const scheduleNext = (hours: number) => {
    const intervalMs = Math.max(1, hours || DEFAULT_EXPIRY_JOB_HOURS) * HOURS;
    timer = setTimeout(run, intervalMs);
  };

  const run = async () => {
    try {
      const now = new Date();

      // Renewal reminders: 7 days and 1 day before expiry
      const inSevenDays = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000);
      const inOneDay = new Date(now.getTime() + 1 * 24 * 60 * 60 * 1000);

      // 7-day reminders
      const expiringIn7 = await (prisma as any).agentSubscription.findMany({
        where: {
          status: 'ACTIVE',
          endDate: { gte: now, lte: inSevenDays },
        },
        select: { id: true, userId: true, endDate: true },
      });

      for (const sub of expiringIn7) {
        const existing = await (prisma as any).subscriptionRenewalReminder.findFirst({
          where: { subscriptionId: sub.id, reminderType: '7_DAYS' },
          select: { id: true },
        });
        if (!existing) {
          await (prisma as any).subscriptionRenewalReminder.create({
            data: {
              subscriptionId: sub.id,
              reminderType: '7_DAYS',
              sentAt: now,
            },
          });
          // Hook for real notification: email/SMS could be sent here.
          console.log('[AgentSubscriptionExpiryJob] 7-day reminder recorded for subscription', sub.id);
        }
      }

      // 1-day reminders
      const expiringIn1 = await (prisma as any).agentSubscription.findMany({
        where: {
          status: 'ACTIVE',
          endDate: { gte: now, lte: inOneDay },
        },
        select: { id: true, userId: true, endDate: true },
      });

      for (const sub of expiringIn1) {
        const existing = await (prisma as any).subscriptionRenewalReminder.findFirst({
          where: { subscriptionId: sub.id, reminderType: '1_DAY' },
          select: { id: true },
        });
        if (!existing) {
          await (prisma as any).subscriptionRenewalReminder.create({
            data: {
              subscriptionId: sub.id,
              reminderType: '1_DAY',
              sentAt: now,
            },
          });
          console.log('[AgentSubscriptionExpiryJob] 1-day reminder recorded for subscription', sub.id);
        }
      }

      // Mark expired subscriptions
      const expired = await (prisma as any).agentSubscription.updateMany({
        where: {
          status: 'ACTIVE',
          endDate: { lt: now },
        },
        data: {
          status: 'EXPIRED',
        },
      });

      if (expired.count && expired.count > 0) {
        // Record simple EXPIRED reminders (final notification hook)
        const expiredSubs = await (prisma as any).agentSubscription.findMany({
          where: { status: 'EXPIRED', endDate: { lt: now } },
          select: { id: true },
        });

        for (const sub of expiredSubs) {
          const existing = await (prisma as any).subscriptionRenewalReminder.findFirst({
            where: { subscriptionId: sub.id, reminderType: 'EXPIRED' },
            select: { id: true },
          });
          if (!existing) {
            await (prisma as any).subscriptionRenewalReminder.create({
              data: {
                subscriptionId: sub.id,
                reminderType: 'EXPIRED',
                sentAt: now,
              },
            });
            console.log('[AgentSubscriptionExpiryJob] Expiry reminder recorded for subscription', sub.id);
          }
        }
      }
    } catch (err) {
      console.error('Agent subscription expiry job failed:', err);
    } finally {
      const hours = Number(process.env.AGENT_SUBSCRIPTION_EXPIRY_JOB_HOURS || DEFAULT_EXPIRY_JOB_HOURS);
      scheduleNext(hours);
    }
  };

  run();

  return () => {
    if (timer) {
      clearTimeout(timer);
    }
  };
};