<?php

namespace App\Listeners;

use App\Models\RestoreRun;
use App\Services\OperationRunService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class SyncRestoreRunToOperation implements ShouldQueue
{
    use InteractsWithQueue;

    public function __construct(
        protected OperationRunService $service
    ) {}

    public function handle(object $event): void
    {
        // We assume we might listen to Eloquent events directly via an observer or manually dispatched events.
        // For now, let's assume we bind this to "RestoreRunCreated" and "RestoreRunUpdated" if they exist,
        // or we treat this class as a generic handler invoked by an Observer.

        // If the event itself HAS a restore run property:
        $restoreRun = null;
        if (property_exists($event, 'restoreRun')) {
            $restoreRun = $event->restoreRun;
        } elseif ($event instanceof RestoreRun) {
            $restoreRun = $event;
        }

        if (! $restoreRun) {
            return;
        }

        $inputs = [
            'restore_run_id' => $restoreRun->id,
            'backup_set_id' => $restoreRun->backup_set_id,
        ];

        // Ensure Run (Idempotent)
        $opRun = $this->service->ensureRun(
            tenant: $restoreRun->tenant,
            type: 'restore.execute',
            inputs: $inputs,
            initiator: $restoreRun->user ?? null, // Assuming RestoreRun has user relation
            initiatorName: $restoreRun->user->name ?? 'System'
        );

        // Map status
        // RestoreRun status -> OperationRun status
        $statusMap = [
            'pending' => 'queued',
            'queued' => 'queued',
            'running' => 'running',
            'completed' => 'completed',
            'failed' => 'completed',
            'cancelled' => 'completed',
            'partially_succeeded' => 'completed',
        ];

        $outcomeMap = [
            'completed' => 'succeeded',
            'failed' => 'failed',
            'cancelled' => 'cancelled',
            'partially_succeeded' => 'partially_succeeded',
        ];

        $newStatus = $statusMap[$restoreRun->status] ?? 'running';
        $newOutcome = $outcomeMap[$restoreRun->status] ?? 'pending';

        $this->service->updateRun(
            run: $opRun,
            status: $newStatus,
            outcome: $newOutcome,
            // We could map counts/failures here if available on RestoreRun
            summaryCounts: $restoreRun->summary_counts ?? [],
            failures: $restoreRun->failures ?? []
        );
    }
}
