<?php

namespace App\Console\Commands;

use App\Models\StockMovement;
use App\Models\StockReservation;
use Illuminate\Console\Command;

class BackfillStockMovementNotesToOrderId extends Command
{
    protected $signature = 'inventory:backfill-stock-movement-notes';

    protected $description = 'Backfill sale stock movements that have "Reservation confirmed: token" notes to "Order #id" using reservation lookup';

    public function handle(): int
    {
        $prefix = 'Reservation confirmed: ';
        $movements = StockMovement::where('type', StockMovement::TYPE_SALE)
            ->where('notes', 'like', $prefix . '%')
            ->get();

        if ($movements->isEmpty()) {
            $this->info('No stock movements with "Reservation confirmed:" notes found.');
            return Command::SUCCESS;
        }

        $updated = 0;
        $skipped = 0;

        foreach ($movements as $movement) {
            $token = substr($movement->notes, strlen($prefix));
            if ($token === false || $token === '') {
                $skipped++;
                continue;
            }

            $reservation = StockReservation::where('reservation_token', $token)->first();
            if (!$reservation || $reservation->order_id === null) {
                $skipped++;
                continue;
            }

            $movement->update(['notes' => "Order #{$reservation->order_id}"]);
            $updated++;
        }

        $this->info("Updated {$updated} stock movement(s). Skipped {$skipped}.");
        return Command::SUCCESS;
    }
}
