<?php

namespace App\Console\Commands;

use App\Models\Warehouse\IncomingOperation;
use App\Models\Warehouse\Project;
use App\Models\Warehouse\StockMovement;
use Illuminate\Console\Command;

class FixMissingProjectSiteOutMovements extends Command
{
    protected $signature = 'fix:missing-out-movements {--dry-run : Show what would be created without actually creating}';
    protected $description = 'Fix missing OUT stock movements for supplier deliveries to project sites';

    public function handle()
    {
        $isDryRun = $this->option('dry-run');

        if ($isDryRun) {
            $this->info('DRY RUN MODE - No changes will be made');
        }

        // Find all completed supplier deliveries to project_site
        $operations = IncomingOperation::where('operation_type', 'supplier_delivery')
            ->where('delivery_type', 'project_site')
            ->whereNotNull('project_id')
            ->where('status', 'completed')
            ->with(['items', 'project'])
            ->get();

        $this->info("Found {$operations->count()} supplier deliveries to project sites");

        $created = 0;
        $skipped = 0;

        foreach ($operations as $operation) {
            foreach ($operation->items as $item) {
                // Check if OUT movement already exists
                $outExists = StockMovement::where('reference_type', 'supplier_delivery')
                    ->where('reference_id', $operation->id)
                    ->where('item_id', $item->item_id)
                    ->where('movement_type', 'out')
                    ->exists();

                if ($outExists) {
                    $skipped++;
                    continue;
                }

                // Find the corresponding IN movement to match timestamp
                $inMovement = StockMovement::where('reference_type', 'supplier_delivery')
                    ->where('reference_id', $operation->id)
                    ->where('item_id', $item->item_id)
                    ->where('movement_type', 'in')
                    ->first();

                if (!$inMovement) {
                    $this->warn("WARNING: No IN movement found for Op #{$operation->id} Item {$item->item_id} - skipping");
                    continue;
                }

                $projectName = $operation->project ? $operation->project->project_name : 'Unknown Project';
                $quantity = $item->quantity_accepted > 0 ? $item->quantity_accepted : $item->quantity_delivered;

                $this->line("Creating OUT movement: Op #{$operation->operation_number} | Item {$item->item_id} | Qty {$quantity} | Project: {$projectName}");

                if (!$isDryRun) {
                    // Create OUT movement with timestamp 1 second after IN movement for correct ordering
                    StockMovement::create([
                        'item_id' => $item->item_id,
                        'movement_type' => 'out',
                        'reference_type' => 'supplier_delivery',
                        'reference_id' => $operation->id,
                        'quantity_before' => 0,
                        'quantity_moved' => $quantity,
                        'quantity_after' => 0,
                        'user_id' => $operation->received_by,
                        'notes' => "Direct delivery to project: {$projectName} - {$operation->operation_number}",
                        'created_at' => $inMovement->created_at->copy()->addSecond(),
                        'updated_at' => $inMovement->updated_at->copy()->addSecond()
                    ]);
                }

                $created++;
            }
        }

        $this->newLine();
        $this->info("Summary:");
        $this->info("- OUT movements " . ($isDryRun ? "to be created" : "created") . ": {$created}");
        $this->info("- Already existing (skipped): {$skipped}");

        if ($isDryRun && $created > 0) {
            $this->newLine();
            $this->warn("Run without --dry-run to actually create the movements");
        }

        return 0;
    }
}
