<?php

namespace App\Console\Commands;

use App\Models\Company;
use App\Models\SubscriptionExpiryReminder;
use App\Notifications\SubscriptionExpiringNotification;
use App\Services\HrmsNotificationService;
use Illuminate\Console\Command;

class SendSubscriptionExpiryReminders extends Command
{
    protected $signature = 'subscriptions:send-expiry-reminders';

    protected $description = 'Email/in-app reminders for licences expiring within 30 days (milestones 30/14/7/3/1/0)';

    private const MILESTONES = [30, 14, 7, 3, 1, 0];

    public function handle(HrmsNotificationService $notifier): int
    {
        $sent = 0;

        $companies = Company::query()
            ->with('subscriptionPlan')
            ->where('status', 'active')
            ->whereNotNull('licence_expire_on')
            ->whereDate('licence_expire_on', '<=', now()->addDays(30)->toDateString())
            ->get();

        foreach ($companies as $company) {
            $days = $company->daysUntilLicenceExpiry();
            if ($days === null || $days > 30) {
                continue;
            }

            if (! in_array($days, self::MILESTONES, true)) {
                continue;
            }

            $key = 'expiring_'.$days;
            $exists = SubscriptionExpiryReminder::query()
                ->where('company_id', $company->id)
                ->where('reminder_key', $key)
                ->exists();

            if ($exists) {
                continue;
            }

            $notification = new SubscriptionExpiringNotification($company, $days);
            $notifier->notifyUsersWithAnyPermission((int) $company->id, ['manage_settings'], $notification);

            SubscriptionExpiryReminder::create([
                'company_id' => $company->id,
                'reminder_key' => $key,
                'sent_at' => now(),
            ]);
            $sent++;
        }

        $this->info("Sent {$sent} expiry reminder(s).");

        return self::SUCCESS;
    }
}
