<?php

namespace App\Jobs;

use App\Models\AuditLog;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Throwable;

class AuditLogJob implements ShouldQueue
{
    use InteractsWithQueue, Queueable, SerializesModels;

    public array $payload;

    public function __construct(array $payload)
    {
        $this->payload = $payload;
    }

    public function handle(): void
    {
        try {
            $data = [
                'franchisee_id' => $this->payload['franchisee_id'] ?? null,
                'user_id'       => $this->payload['user_id'] ?? null,
                'action'        => $this->payload['action'] ?? 'unknown',
                'description'   => $this->payload['description'] ?? null,
                'ip_address'    => $this->payload['ip_address'] ?? null,
                'created_at'    => now(),
            ];

            AuditLog::create($data);
        } catch (Throwable $e) {
            \Log::error('AuditLogJob failed', ['err' => $e->getMessage(), 'payload' => $this->payload]);
        }
    }
}
