<?php

namespace App\Console\Commands;

use App\Models\Subscription;
use App\Services\BillingService;
use Illuminate\Console\Command;

class UpdateDriverCountCharges extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'billing:update-driver-charges';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Update subscription charges when driver count changes';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $billingService = app(BillingService::class);

        $subscriptions = Subscription::where('status', 'active')
            ->with(['user', 'user.company', 'package'])
            ->get();

        if ($subscriptions->isEmpty()) {
            $this->info('No active subscriptions.');
            return 0;
        }

        $this->info("Checking {$subscriptions->count()} subscriptions...");

        $updated = 0;

        foreach ($subscriptions as $subscription) {
            try {
                $currentDriverCount = $subscription->user->company->drivers()->count();
                $lastRecordedCount = $subscription->last_driver_count ?? 0;

                if ($currentDriverCount !== $lastRecordedCount) {
                    $this->line("Subscription {$subscription->id}: Driver count changed from {$lastRecordedCount} to {$currentDriverCount}");

                    $billingService->handleDriverCountChange($subscription);

                    $updated++;
                    $this->info("✓ Updated charges for subscription {$subscription->id}");
                }
            } catch (\Exception $e) {
                $this->error("✗ Failed to update subscription {$subscription->id}: {$e->getMessage()}");
            }
        }

        $this->info("Updated {$updated} subscription(s).");
        return 0;
    }
}
