<?php

namespace App\Console\Commands;

use App\Models\OperationalDocument;
use App\Models\TradeDocument;
use Illuminate\Console\Command;

class VerifyOperationalWorkflow extends Command
{
    protected $signature = 'crm:verify-operational-workflow {reference=QA-E2E-SO-001 : Sales Order reference to validate}';
    protected $description = 'Verify the quotation-to-invoice operational workflow linkage without changing data';

    public function handle(): int
    {
        $order = OperationalDocument::withoutGlobalScopes()->where('type', 'sales-orders')
            ->where('reference_number', $this->argument('reference'))->first();
        if (! $order) {
            $this->error('Sales Order was not found.');
            return self::FAILURE;
        }
        $quote = $order->trade_document_id ? TradeDocument::withoutGlobalScopes()->find($order->trade_document_id) : null;
        $expected = ['contracts', 'handovers', 'deliveries', 'invoices'];
        $current = $order;
        foreach ($expected as $type) {
            $current = OperationalDocument::withoutGlobalScopes()->where('parent_id', $current->id)->where('type', $type)->first();
            if (! $current) {
                $this->error("Missing {$type} after {$order->reference_number}.");
                return self::FAILURE;
            }
            $this->line("✓ {$type}: {$current->reference_number} ({$current->status})");
        }
        if (! $quote || $quote->type !== 'quotation' || $quote->status !== 'accepted') {
            $this->error('The Sales Order is not linked to an accepted quotation.');
            return self::FAILURE;
        }
        if (! $current->trade_document_id || ! TradeDocument::withoutGlobalScopes()->whereKey($current->trade_document_id)->where('type', 'invoice')->exists()) {
            $this->error('The final operational invoice is not linked to a financial invoice.');
            return self::FAILURE;
        }
        $this->info('Operational workflow verification passed.');
        return self::SUCCESS;
    }
}
