<?php

namespace App\Console\Commands;

use App\Models\Warehouse\DivisionDelivery;
use App\Models\Warehouse\Inventory;
use Illuminate\Console\Command;

class SyncDivisionDeliveryInventory extends Command
{
    protected $signature = 'sync:division-delivery-inventory
                            {--dry-run : Show what would be updated without making changes}
                            {--division= : Only sync specific division ID}
                            {--item= : Only sync specific item ID}';

    protected $description = 'Sync DivisionDelivery.current_available_quantity with actual Inventory quantities';

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

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

        $this->info('Syncing DivisionDelivery with Inventory...');
        $this->newLine();

        $query = DivisionDelivery::with(['item', 'division']);

        if ($divisionFilter) {
            $query->where('division_id', $divisionFilter);
        }

        if ($itemFilter) {
            $query->where('item_id', $itemFilter);
        }

        $records = $query->get();

        $synced = 0;
        $skipped = 0;
        $mismatches = [];

        foreach ($records as $dd) {
            // Calculate actual inventory quantity for this division/item
            $actualQty = Inventory::where('item_id', $dd->item_id)
                ->where('division_id', $dd->division_id)
                ->sum('quantity_available');

            // Check if there's a mismatch (tolerance of 0.01 for floating point)
            if (abs($dd->current_available_quantity - $actualQty) > 0.01) {
                $itemCode = $dd->item->item_code ?? 'N/A';
                $divisionName = $dd->division->division_name ?? 'N/A';

                $mismatches[] = [
                    'item_code' => $itemCode,
                    'division' => $divisionName,
                    'dd_qty' => $dd->current_available_quantity,
                    'inv_qty' => $actualQty,
                    'diff' => $actualQty - $dd->current_available_quantity
                ];

                $this->line("Mismatch: {$itemCode} | {$divisionName}");
                $this->line("  DivisionDelivery: {$dd->current_available_quantity}");
                $this->line("  Inventory: {$actualQty}");
                $this->line("  Difference: " . ($actualQty - $dd->current_available_quantity));

                if (!$isDryRun) {
                    $dd->current_available_quantity = $actualQty;
                    $dd->last_updated = now();
                    $dd->save();
                    $this->info("  -> SYNCED");
                }

                $this->newLine();
                $synced++;
            } else {
                $skipped++;
            }
        }

        $this->newLine();
        $this->info("=== Summary ===");
        $this->info("Total records checked: " . $records->count());
        $this->info("Already in sync: {$skipped}");

        if ($isDryRun) {
            $this->info("Would be synced: {$synced}");
        } else {
            $this->info("Synced: {$synced}");
        }

        if ($isDryRun && $synced > 0) {
            $this->newLine();
            $this->warn("Run without --dry-run to apply the sync");
        }

        return 0;
    }
}
