<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\StockOpname;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;

class UnlockStockOpnames extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'stockopname:unlock';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Unlock Stock Opname documents that have been locked for more than 3 minutes';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $threeMinutesAgo = Carbon::now()->subMinutes(3);
        
        // Find all locked SO that have been locked for more than 3 minutes
        $lockedSOs = StockOpname::whereNotNull('editing_by')
            ->whereNotNull('editing_at')
            ->where('editing_at', '<', $threeMinutesAgo)
            ->get();
        
        if ($lockedSOs->isEmpty()) {
            $this->info('No locked Stock Opname documents found.');
            Log::channel('schedule_laravel')->info('stockopname:unlock - No locked documents found.');
            return 0;
        }
        
        $unlockedCount = 0;
        
        foreach ($lockedSOs as $so) {
            $oldEditingBy = $so->editing_by;
            $oldEditingAt = $so->editing_at;
            
            $so->update([
                'editing_by' => null,
                'editing_at' => null
            ]);
            
            $unlockedCount++;
            
            Log::info('Stock Opname auto-unlocked', [
                'so_id' => $so->id,
                'so_number' => $so->so_number,
                'was_editing_by' => $oldEditingBy,
                'locked_since' => $oldEditingAt,
                'locked_duration_minutes' => $oldEditingAt->diffInMinutes(now())
            ]);
        }
        
        $this->info("Successfully unlocked {$unlockedCount} Stock Opname document(s).");
        Log::channel('schedule_laravel')->info("stockopname:unlock - Unlocked {$unlockedCount} document(s).");
        
        return 0;
    }
}
