<?php

namespace App\Console\Commands;

use App\Models\Tenant;
use App\Services\SubscriptionService;
use Illuminate\Console\Command;

class ProcessAutoRenewals extends Command
{
    protected $signature = 'billing:process-auto-renewals {--dry-run : Show due renewals without charging them}';

    protected $description = 'Process tenants with due automatic subscription renewals.';

    public function handle(SubscriptionService $subscriptions): int
    {
        $query = Tenant::query()
            ->with('plan')
            ->where('auto_billing_enabled', true)
            ->where('auto_billing_status', 'active')
            ->whereNotNull('auto_billing_next_charge_at')
            ->where('auto_billing_next_charge_at', '<=', now());

        $dueTenants = $query->get();

        if ($dueTenants->isEmpty()) {
            $this->info('No automatic renewals are due.');

            return self::SUCCESS;
        }

        foreach ($dueTenants as $tenant) {
            $this->line('Processing '.$tenant->name.'...');

            if ($this->option('dry-run')) {
                continue;
            }

            try {
                $invoice = $subscriptions->createAutoRenewalPayment($tenant);

                if ($invoice) {
                    $this->info('Renewed '.$tenant->name.' with invoice '.$invoice->invoice_number.'.');
                }
            } catch (\Throwable $exception) {
                $tenant->update([
                    'auto_billing_status' => 'failed',
                    'auto_billing_failed_at' => now(),
                    'auto_billing_failure_reason' => $exception->getMessage(),
                ]);

                $this->error('Failed '.$tenant->name.': '.$exception->getMessage());
            }
        }

        return self::SUCCESS;
    }
}
