<?php

namespace App\Console\Commands;

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

class CheckExpiredSubscriptions extends Command
{
    protected $signature = 'subscriptions:check-expired';
    protected $description = 'Deaktiviert abgelaufene Subscriptions und setzt User auf Free-Plan zurück';

    public function handle(): void
    {
        $expired = Subscription::whereIn('status', [
                SubscriptionStatus::Active->value,
                SubscriptionStatus::Gifted->value,
            ])
            ->whereNotNull('ends_at')
            ->where('ends_at', '<', now())
            ->with('user')
            ->get();

        $freePlan = Plan::freePlan();

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

            if ($freePlan && $sub->user) {
                $sub->user->subscriptions()->create([
                    'plan_id'   => $freePlan->id,
                    'plan_name' => $freePlan->name,
                    'plan_slug' => $freePlan->plan_key ?? str($freePlan->name)->slug(),
                    'price'     => 0,
                    'interval'  => 'monthly',
                    'status'    => SubscriptionStatus::Active->value,
                    'starts_at' => now(),
                    'ends_at'   => null,
                ]);
            }

            $this->info("Subscription von {$sub->user?->name} abgelaufen.");
        }

        $this->info("{$expired->count()} Subscriptions deaktiviert.");
    }
}
