<?php

namespace App\Listeners\Manufacturing;

use App\Events\Manufacturing\ProcessStatusChanged;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Log;

class UpdateRouteCardProgress implements ShouldQueue
{
    use InteractsWithQueue;

    public function handle(ProcessStatusChanged $event): void
    {
        $process = $event->process;
        $routeCard = $process->routeCard;

        if (!$routeCard) {
            return;
        }

        Log::info('Process status changed', [
            'process_id' => $process->id,
            'route_card_id' => $routeCard->id,
            'previous_status' => $event->previousStatus,
            'new_status' => $event->newStatus,
            'triggered_by' => $event->userId,
        ]);

        // Calculate route card progress
        $totalProcesses = $routeCard->processes()->count();
        $completedProcesses = $routeCard->processes()->where('status', 'completed')->count();

        $progress = $totalProcesses > 0
            ? round(($completedProcesses / $totalProcesses) * 100)
            : 0;

        // Update route card status based on process completion
        if ($completedProcesses === $totalProcesses && $totalProcesses > 0) {
            $routeCard->update(['status' => 'completed']);

            Log::info('Route card completed', [
                'route_card_id' => $routeCard->id,
            ]);
        } elseif ($event->newStatus === 'in_progress' && $routeCard->status === 'pending') {
            $routeCard->update(['status' => 'in_progress']);
        }
    }
}
