<?php

namespace App\Domain\Financial\Listeners;

use App\Domain\Financial\Events\InvoicePaid;
use App\Domain\Training\Models\Enrollment;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;

class ActivateEnrollmentOnPayment implements ShouldQueue
{
    public function handle(InvoicePaid $event): void
    {
        try {
            $invoice = $event->invoice;

            $pendingEnrollments = Enrollment::where('invoice_id', $invoice->id)
                ->where('status', 'pending')
                ->get();

            foreach ($pendingEnrollments as $enrollment) {
                $enrollment->update([
                    'status' => 'active',
                    'activated_at' => now(),
                ]);
            }
        } catch (\Throwable $e) {
            Log::error('ActivateEnrollmentOnPayment failed: ' . $e->getMessage(), [
                'invoice_id' => $event->invoice->id,
            ]);
        }
    }

    public function failed(InvoicePaid $event, \Throwable $exception): void
    {
        Log::critical('ActivateEnrollmentOnPayment PERMANENTLY FAILED', [
            'invoice_id' => $event->invoice->id,
            'error' => $exception->getMessage(),
        ]);
    }
}
