<?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 SuspendExpiredSubscriptions extends Command
{
    protected $signature = 'subscriptions:suspend-expired';

    protected $description = 'Auto-suspend companies whose licence_expire_on is past';

    public function handle(HrmsNotificationService $notifier): int
    {
        $companies = Company::query()
            ->with('subscriptionPlan')
            ->where('status', 'active')
            ->whereNotNull('licence_expire_on')
            ->whereDate('licence_expire_on', '<', now()->toDateString())
            ->get();

        $count = 0;
        foreach ($companies as $company) {
            $company->forceFill(['status' => 'suspended'])->save();

            $key = 'suspended_'.($company->licence_expire_on?->format('Y-m-d') ?? 'unknown');
            $exists = SubscriptionExpiryReminder::query()
                ->where('company_id', $company->id)
                ->where('reminder_key', $key)
                ->exists();

            if (! $exists) {
                $notification = new SubscriptionExpiringNotification($company, -1, true);
                $notifier->notifyUsersWithAnyPermission((int) $company->id, ['manage_settings'], $notification);
                SubscriptionExpiryReminder::create([
                    'company_id' => $company->id,
                    'reminder_key' => $key,
                    'sent_at' => now(),
                ]);
            }

            $count++;
        }

        $this->info("Suspended {$count} company(ies).");

        return self::SUCCESS;
    }
}
