<?php

namespace App\Listeners\Manufacturing;

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

class ProcessQcApproval implements ShouldQueue
{
    use InteractsWithQueue;

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

        Log::info('QC Approval completed', [
            'process_id' => $process->id,
            'stage' => $event->stage,
            'status' => $event->status,
            'triggered_by' => $event->userId,
        ]);

        // Update process status based on QC stage and result
        if ($event->status === 'approved') {
            $nextStatus = $this->getNextStatus($event->stage, $process->status);

            if ($nextStatus) {
                $process->update(['status' => $nextStatus]);

                Log::info('Process status updated after QC approval', [
                    'process_id' => $process->id,
                    'new_status' => $nextStatus,
                ]);
            }
        } elseif ($event->status === 'rejected') {
            $process->update(['status' => 'on_hold']);

            Log::warning('Process put on hold due to QC rejection', [
                'process_id' => $process->id,
            ]);
        }
    }

    protected function getNextStatus(string $stage, string $currentStatus): ?string
    {
        $transitions = [
            'qc_before' => 'in_progress',
            'qc_during' => 'qc_after',
            'qc_after' => 'completed',
        ];

        return $transitions[$currentStatus] ?? null;
    }
}
