<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Modules\Invoices\InvoiceItem;
use App\Modules\Stock\StockTransaction;
use Illuminate\Support\Facades\DB;

class FixCompositeBuildsStock extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'stock:fix-composite-builds {--dry-run : Run without making changes}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Fix stock transactions for composite/build items sold via invoices';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $dryRun = $this->option('dry-run');

        if ($dryRun) {
            $this->info('Running in DRY-RUN mode - no changes will be made');
        }

        // Find all invoice items with composite stock items
        $invoiceItems = InvoiceItem::with(['stock.composite_items', 'invoice'])
            ->whereHas('stock', function ($query) {
                $query->where('composite', 1);
            })
            ->whereNull('deleted_at')
            ->get();

        $this->info("Found {$invoiceItems->count()} invoice items with composite builds");

        $fixed = 0;
        $errors = 0;

        foreach ($invoiceItems as $item) {
            try {
                $this->processInvoiceItem($item, $dryRun);
                $fixed++;
            } catch (\Exception $e) {
                $this->error("Error processing invoice item {$item->id}: {$e->getMessage()}");
                $errors++;
            }
        }

        $this->info("\n=== Summary ===");
        $this->info("Processed: {$invoiceItems->count()}");
        $this->info("Fixed: {$fixed}");
        $this->info("Errors: {$errors}");

        if ($dryRun) {
            $this->warn("\nThis was a DRY-RUN. Run without --dry-run to apply changes.");
        }

        return 0;
    }

    protected function processInvoiceItem($item, $dryRun)
    {
        if (!$item->stock || !$item->stock->composite) {
            return;
        }

        $this->line("\n--- Invoice #{$item->invoice_id}, Item: {$item->name} (Qty: {$item->quantity}) ---");

        // Check if main stock transaction exists
        $mainTransaction = StockTransaction::where('related_type', $item->invoice->type)
            ->where('related_id', $item->invoice_id)
            ->where('stock_id', $item->stock_id)
            ->first();

        if (!$mainTransaction) {
            $this->warn("  Missing main stock transaction for {$item->stock->name}");

            if (!$dryRun) {
                DB::transaction(function () use ($item) {
                    StockTransaction::createOrUpdate(
                        $item->invoice->type,
                        $item->invoice_id,
                        $item->stock_id,
                        $item->quantity * -1
                    );
                });
                $this->info("  ✓ Created main stock transaction: -{$item->quantity}");
            } else {
                $this->info("  [DRY-RUN] Would create main stock transaction: -{$item->quantity}");
            }
        } else {
            $this->comment("  Main stock transaction already exists");
        }

        // Process component stock
        foreach ($item->stock->composite_items as $component) {
            $quantityNeeded = $component->pivot->quantity * $item->quantity;

            $componentTransaction = StockTransaction::where('related_type', $item->invoice->type)
                ->where('related_id', $item->invoice_id)
                ->where('stock_id', $component->id)
                ->first();

            if (!$componentTransaction) {
                $this->warn("  Missing component transaction: {$component->name} (Need: {$quantityNeeded})");

                if (!$dryRun) {
                    DB::transaction(function () use ($item, $component, $quantityNeeded) {
                        StockTransaction::createOrUpdate(
                            $item->invoice->type,
                            $item->invoice_id,
                            $component->id,
                            $quantityNeeded * -1
                        );
                    });
                    $this->info("  ✓ Created component transaction for {$component->name}: -{$quantityNeeded}");
                } else {
                    $this->info("  [DRY-RUN] Would create component transaction for {$component->name}: -{$quantityNeeded}");
                }
            } else {
                $this->comment("  Component transaction already exists for {$component->name}");
            }
        }
    }
}
