import { queryWithRLS } from "../db";
async function expireTrials() {
  const result = { processed: 0, errors: [] };
  const expiredTrials = await queryWithRLS(
    `SELECT id, "teamId" FROM subscriptions
     WHERE status = 'trialing'
       AND "trialEndsAt" < NOW()
       AND "externalSubscriptionId" IS NULL
     FOR UPDATE SKIP LOCKED`
  );
  console.log(`[lifecycle-job] Found ${expiredTrials.length} trials to expire`);
  for (const trial of expiredTrials) {
    try {
      await queryWithRLS(
        `UPDATE subscriptions
         SET status = 'expired', "updatedAt" = NOW()
         WHERE id = $1`,
        [trial.id]
      );
      await logLifecycleEvent(trial.id, "trial_expired");
      result.processed++;
    } catch (error) {
      result.errors.push(`Failed to expire trial ${trial.id}: ${error}`);
    }
  }
  return result;
}
async function handlePastDueGracePeriod() {
  const result = { processed: 0, errors: [] };
  const expiredPastDue = await queryWithRLS(
    `SELECT id FROM subscriptions
     WHERE status = 'past_due'
       AND "updatedAt" < NOW() - INTERVAL '3 days'
     FOR UPDATE SKIP LOCKED`
  );
  console.log(`[lifecycle-job] Found ${expiredPastDue.length} past_due subscriptions to expire`);
  for (const sub of expiredPastDue) {
    try {
      await queryWithRLS(
        `UPDATE subscriptions
         SET status = 'expired', "updatedAt" = NOW()
         WHERE id = $1`,
        [sub.id]
      );
      await logLifecycleEvent(sub.id, "past_due_expired");
      result.processed++;
    } catch (error) {
      result.errors.push(`Failed to expire past_due ${sub.id}: ${error}`);
    }
  }
  return result;
}
async function resetMonthlyUsage() {
  const result = { processed: 0, errors: [] };
  const now = /* @__PURE__ */ new Date();
  const currentMonth = now.getMonth() + 1;
  const currentYear = now.getFullYear();
  const previousMonth = currentMonth === 1 ? 12 : currentMonth - 1;
  const previousYear = currentMonth === 1 ? currentYear - 1 : currentYear;
  const previousPeriodKey = `${previousYear}-${String(previousMonth).padStart(2, "0")}`;
  console.log(`[lifecycle-job] Archiving usage for period: ${previousPeriodKey}`);
  const archived = await queryWithRLS(
    `UPDATE usage
     SET metadata = jsonb_set(COALESCE(metadata, '{}'::jsonb), '{archived}', 'true')
     WHERE "periodKey" = $1
       AND (metadata->>'archived') IS NULL
     RETURNING id`,
    [previousPeriodKey]
  );
  result.processed = archived.length;
  console.log(`[lifecycle-job] Archived ${archived.length} usage records`);
  return result;
}
async function logLifecycleEvent(subscriptionId, eventType) {
  await queryWithRLS(
    `INSERT INTO "billing_events" ("subscriptionId", type, status, amount, currency, metadata)
     VALUES ($1, 'lifecycle', 'succeeded', 0, 'usd', $2)`,
    [subscriptionId, JSON.stringify({ event: eventType, timestamp: (/* @__PURE__ */ new Date()).toISOString() })]
  );
}
export {
  expireTrials,
  handlePastDueGracePeriod,
  resetMonthlyUsage
};
