<?php

namespace App\Listeners;

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

class LockAndUnverifyAssociation implements ShouldQueue
{
    use InteractsWithQueue;

    /**
     * Handle the event.
     */
    public function handle(AssociationProfileCompleted $event): void
    {
        Log::channel('queue')->info('Processing AssociationProfileCompleted event', [
            'association_id' => $event->association->id,
            'association_email' => $event->associationEmail,
            'previous_completion' => $event->previousCompletionPercentage,
            'current_completion' => $event->currentCompletionPercentage,
        ]);

        try {
            // Lock the profile and require re-verification when profile is completed
            $event->association->update([
                'is_locked' => true,
                'is_verified' => false,
            ]);

            Log::channel('queue')->info('Association profile automatically locked and unverified', [
                'association_id' => $event->association->id,
                'association_email' => $event->associationEmail,
            ]);

            // Log the automatic action for audit purposes
            activity()
                ->performedOn($event->association)
                ->withProperties([
                    'previous_completion' => $event->previousCompletionPercentage,
                    'current_completion' => $event->currentCompletionPercentage,
                    'action' => 'auto_locked_and_unverified',
                ])
                ->log('Profile automatically locked and marked for verification after completion');
        } catch (\Exception $e) {
            Log::channel('queue')->error('Failed to process AssociationProfileCompleted event', [
                'association_id' => $event->association->id,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);

            throw $e; // Re-throw to trigger queue retry
        }
    }

    /**
     * Handle a job failure.
     */
    public function failed(AssociationProfileCompleted $event, \Throwable $exception): void
    {
        Log::channel('queue')->critical('AssociationProfileCompleted event processing failed permanently', [
            'association_id' => $event->association->id,
            'association_email' => $event->associationEmail,
            'error' => $exception->getMessage(),
            'trace' => $exception->getTraceAsString(),
        ]);
    }
}
