<?php

namespace App\Console\Commands;

use App\Models\Location;
use App\Models\Product;
use App\Services\LocationInventoryService;
use App\Services\LocationService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class InventoryCutoverCheck extends Command
{
    protected $signature = 'inventory:cutover-check';

    protected $description = 'Pre-flight checks for multi-store production cutover (does not mutate data)';

    public function handle(LocationService $locations, LocationInventoryService $inventory): int
    {
        $this->info('Multi-store cutover check (read-only)');
        $this->newLine();

        if (!$inventory->useLocationInventory()) {
            $this->error('inventory_balances / stock_ledger tables missing. Run migrations first.');

            return self::FAILURE;
        }

        $locations->ensureCompanyAndDefaults();
        $store = Location::defaultStore();
        $warehouse = Location::centralWarehouse();

        $this->table(['Key', 'Value'], [
            ['Default store', $store ? "{$store->id} — {$store->name}" : 'MISSING'],
            ['Central warehouse', $warehouse ? "{$warehouse->id} — {$warehouse->name}" : 'MISSING'],
            ['Store fulfills_online', $store ? ((int) $store->fulfills_online) : '-'],
            ['Warehouse fulfills_online', $warehouse ? ((int) $warehouse->fulfills_online) : '-'],
        ]);

        if (!$store) {
            $this->error('Default store missing — cutover cannot proceed.');

            return self::FAILURE;
        }

        $parentsWithStock = Product::query()
            ->whereNull('parent_id')
            ->where('current_stock', '>', 0)
            ->count();

        $missingBalances = (int) (DB::selectOne("
            SELECT COUNT(*) AS c FROM products p
            WHERE p.current_stock > 0
              AND NOT EXISTS (SELECT 1 FROM inventory_balances b WHERE b.product_id = p.id)
        ")->c ?? 0);

        $byLoc = DB::table('inventory_balances')
            ->select('location_id', DB::raw('COUNT(*) as row_count'), DB::raw('SUM(on_hand) as on_hand_sum'))
            ->groupBy('location_id')
            ->get();

        $this->newLine();
        $this->info("Parents with current_stock > 0: {$parentsWithStock}");
        $this->info("Products with stock but NO balance rows: {$missingBalances}");
        $this->newLine();
        $this->info('Balances by location:');
        foreach ($byLoc as $row) {
            $loc = Location::find($row->location_id);
            $name = $loc?->name ?? 'unknown';
            $this->line("  #{$row->location_id} {$name}: rows={$row->row_count} on_hand_sum={$row->on_hand_sum}");
        }

        $this->newLine();
        $this->warn('Production cutover (store-first) — run only when ready:');
        $this->line('  1. Backup DB');
        $this->line('  2. Deploy + php artisan migrate --force');
        $this->line('  3. php artisan inventory:cutover-check');
        $this->line("  4. php artisan inventory:backfill-locations --location={$store->id}");
        $this->line('  5. Verify POS sell + online in-stock + admin Products stock at Warangal');
        $this->line('  6. Do NOT backfill into warehouse while POS sells from store');
        $this->line('  7. Never re-run backfill on live data');

        if ($missingBalances > 0) {
            $this->newLine();
            $this->warn("{$missingBalances} SKUs still need store backfill before go-live.");
        } else {
            $this->newLine();
            $this->info('No missing balance rows for products with current_stock > 0.');
        }

        return self::SUCCESS;
    }
}
