<?php

namespace App\Console\Commands;

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

/**
 * Scheduled command to check for expired subscriptions.
 * When a client's subscription expires:
 * 1. Invalidates all active user sessions under that client
 * 2. Sets force_logout flag on all users so they're kicked immediately
 * 3. Disables SMS/promotion services for all users
 * 
 * Run via: php artisan subscriptions:check-expired
 * Schedule: Every 5 minutes (configured in Console/Kernel.php)
 */
class CheckExpiredSubscriptions extends Command
{
    protected $signature = 'subscriptions:check-expired';
    protected $description = 'Check for expired subscriptions and force logout all users, stop all services';

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

        // Find clients whose subscription just expired (was active but now expired)
        // We look for clients that are still marked as subscription_active but the date has passed
        $expiredClients = Client::where('is_subscription_active', true)
            ->where(function ($query) {
                $query->where(function ($q) {
                    // Trial expired
                    $q->where('subscription_type', 'trial')
                        ->whereNotNull('trial_ends_at')
                        ->where('trial_ends_at', '<', now());
                })->orWhere(function ($q) {
                    // Subscription expired (non-trial)
                    $q->where('subscription_type', '!=', 'trial')
                        ->whereNotNull('subscription_ends_at')
                        ->where('subscription_ends_at', '<', now());
                });
            })
            ->get();

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

        $totalUsersAffected = 0;
        $totalSessionsInvalidated = 0;

        foreach ($expiredClients as $client) {
            $this->warn("Subscription expired for client: {$client->name} (ID: {$client->id})");

            // Mark subscription as inactive
            $client->update(['is_subscription_active' => false]);

            // Get all users under this client
            $users = User::where('client_id', $client->id)->get();

            foreach ($users as $user) {
                // Set force logout flag
                $user->update([
                    'force_logout' => true,
                    'force_logout_reason' => 'subscription_expired',
                    'sms_service_enabled' => false,
                    'promotions_enabled' => false,
                ]);

                // Invalidate all active sessions
                $invalidated = UserSession::where('user_id', $user->id)
                    ->where('is_active', true)
                    ->update(['is_active' => false]);

                $totalSessionsInvalidated += $invalidated;
                $totalUsersAffected++;
            }

            Log::warning('Subscription expired - all users force logged out', [
                'client_id' => $client->id,
                'client_name' => $client->name,
                'users_affected' => $users->count(),
            ]);

            $this->info("  → {$users->count()} users force logged out, services disabled");
        }

        $this->info("Done. Clients: {$expiredClients->count()}, Users affected: {$totalUsersAffected}, Sessions invalidated: {$totalSessionsInvalidated}");

        return Command::SUCCESS;
    }
}
