<?php

namespace App\Console\Commands;

use App\Enums\CompanyStatus;
use App\Enums\SubscriptionStatus;
use App\Models\Subscription;
use Illuminate\Console\Command;

class CheckSubscriptionExpirations extends Command
{
    protected $signature   = 'subscriptions:check-expirations';
    protected $description = 'Marca como vencidas las suscripciones que pasaron su current_period_end + days_grace y suspende las empresas correspondientes.';

    public function handle(): int
    {
        $graceDays = (int) config('reservapro.grace_days', 3);
        $cutoff    = now()->subDays($graceDays);

        $expired = Subscription::query()
            ->withoutGlobalScopes()
            ->with('company')
            ->whereIn('status', ['trial', 'active', 'past_due'])
            ->whereNotNull('current_period_end')
            ->where('current_period_end', '<', $cutoff)
            ->get();

        foreach ($expired as $sub) {
            $sub->update([
                'status'   => SubscriptionStatus::Expired,
                'ended_at' => now(),
            ]);

            if ($sub->company && $sub->company->status !== CompanyStatus::Suspended) {
                $sub->company->update([
                    'status'             => CompanyStatus::Suspended,
                    'suspended_at'       => now(),
                    'suspension_reason'  => 'Suscripción vencida',
                ]);
                $this->info("Empresa {$sub->company->name} suspendida por suscripción vencida.");
            }
        }

        $this->info("Suscripciones procesadas: {$expired->count()}");
        return self::SUCCESS;
    }
}
