<?php

namespace App\Modules\Admin\Billing\Services;

use App\Modules\Admin\Tenancy\Repositories\SubscriptionRepository;
use Illuminate\Support\Carbon;

class RenewalReminderService
{
    public function __construct(
        private readonly SubscriptionRepository $subscriptions,
        private readonly BillingAuditService $billingAudit,
    ) {}

    /**
     * Queue renewal reminder audit rows for subscriptions ending within the horizon (days).
     */
    public function dispatchRenewalReminders(int $withinDays = 7): int
    {
        $from = Carbon::now()->startOfDay();
        $to = Carbon::now()->addDays($withinDays)->endOfDay();
        $rows = $this->subscriptions->renewingActiveBetween($from, $to);
        $n = 0;
        foreach ($rows as $sub) {
            $tid = (int) $sub->tenant_id;
            $this->billingAudit->logSystem($tid, 'renewal_reminder.window', [
                'subscription_id' => (int) $sub->id,
                'ends_at' => $sub->ends_at?->toIso8601String(),
                'plan_id' => (int) $sub->plan_id,
            ]);
            $n++;
        }

        return $n;
    }
}
