<?php

namespace App\Jobs;

use App\Services\VoiceService;
use App\Models\VoiceLog;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class SendVoiceJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    private $data;

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

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $contact = $this->data['contact'];
        $voice_file_path = $this->data['voice_file_path'];
        $caller_id = $this->data['caller_id'] ?? null;
        $retry_count = $this->data['retry_count'] ?? 0;
        $type = $this->data['type'] ?? 'voice_send';

        $result = (new VoiceService)->send_voice($contact, $voice_file_path, $caller_id, $retry_count);

        VoiceLog::create([
            'contact' => $contact,
            'callerid' => $caller_id,
            'type' => $type,
            'voice_file' => $this->data['voice_file'] ?? null,
            'call_status' => $result['call_status'] ?? 'Failed',
            'message' => $result['message'] ?? null,
            'retry_count' => $retry_count,
            'blast_id' => ($result['success'] ?? false) ? ($result['blast_id'] ?? null) : null,
        ]);
        if (!($result['success'] ?? false)) {
            $this->fail(new \RuntimeException($result['message'] ?? 'Voice call send failed.'));
            return $result;
        }
        return $result;
    }
}
