<?php

namespace App\Console\Commands;

use App\Models\Invoice;
use App\Services\WhmcsProvisioningService;
use Illuminate\Console\Command;

class ReconcileWhmcsProvisioning extends Command
{
    protected $signature = 'whmcs:reconcile-provisioning
        {invoice : Local invoice id or WHMCS invoice id}
        {--whmcs : Treat the value as a WHMCS invoice id}
        {--force-items : Also run direct ModuleCreate/DomainRegister/DomainTransfer for invoice items}';

    protected $description = 'Verify a paid WHMCS invoice and reconcile its hosting/domain provisioning';

    public function handle(WhmcsProvisioningService $provisioning): int
    {
        $value = (int) $this->argument('invoice');
        $invoice = $this->option('whmcs')
            ? Invoice::where('whmcs_invoice_id', $value)->first()
            : Invoice::find($value);

        if (! $invoice) {
            $this->error('Invoice not found. Use --whmcs when providing the WHMCS invoice number.');
            return self::FAILURE;
        }

        $invoice->loadMissing('order');
        $user = $invoice->user_id ? \App\Models\User::find($invoice->user_id) : null;
        if (! $user) {
            $this->error('The local invoice has no valid user.');
            return self::FAILURE;
        }

        try {
            $report = $provisioning->reconcilePaidInvoice($user, $invoice, (bool) $this->option('force-items'));
            $this->line(json_encode($report, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));

            return ($report['ok'] ?? false) ? self::SUCCESS : self::FAILURE;
        } catch (\Throwable $e) {
            $this->error($e->getMessage());
            return self::FAILURE;
        }
    }
}
