<?php

namespace App\Console\Commands;

use App\Models\Subscription;
use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class CheckExpiredSubscriptions extends Command
{
    protected $signature   = 'invotrack:check-subscriptions';
    protected $description = 'Downgrade users whose subscription has expired';

    public function handle(): int
    {
        $this->info('Checking expired subscriptions...');

        // Find active subscriptions that have expired
        $expired = Subscription::where('status', 'active')
            ->where('expires_at', '<', now())
            ->with('user')
            ->get();

        if ($expired->isEmpty()) {
            $this->info('No expired subscriptions found.');
            return self::SUCCESS;
        }

        foreach ($expired as $subscription) {
            try {
                // Mark subscription as expired
                $subscription->update(['status' => 'expired']);

                // Downgrade user to free plan
                $subscription->user->update([
                    'plan'            => 'free',
                    'plan_expires_at' => null,
                ]);

                $this->line("  ✓ Expired: {$subscription->user->email} ({$subscription->plan_label} → Free)");

                Log::info("Subscription expired: user {$subscription->user_id}, plan {$subscription->plan}");

            } catch (\Exception $e) {
                $this->error("  ✗ Failed for user {$subscription->user_id}: {$e->getMessage()}");
                Log::error("Subscription expiry failed: " . $e->getMessage());
            }
        }

        $this->info("Done. {$expired->count()} subscription(s) expired.");
        return self::SUCCESS;
    }
}
