<?php

namespace App\Http\Controllers;

use App\Models\Job;
use App\Services\SentSmsService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CornJobController extends Controller
{
    public function runJob(SentSmsService $sentSmsService)
    {
        $job = DB::table('jobs')
            ->where('attempts', 0)
            ->whereNull('reserved_at')
            ->orderBy('id', 'ASC')
            ->first();

        if (!$job) {
            return true;
        }

        $payload = json_decode($job->payload);
        $jobData = unserialize($payload->data->command);

        try {

            DB::table('jobs')->where('id', $job->id)
                ->update([
                    'attempts' => 1,
                    'reserved_at' => time(),
                ]);

            $jobStatus = $sentSmsService->smsSentJob($jobData->data);

            if ($jobStatus) {
                DB::table('jobs')->where('id', $job->id)->delete();
                DB::table('jobs_histories')->where('id', $jobData->history->id)->update(['status' => 1]);
            } else {
                DB::table('jobs_histories')->where('id', $jobData->history->id)->update(['status' => 0]);
            }

        } catch (\Exception $exception) {
            insertFailLog(0, $exception->getMessage());
            DB::table('jobs')->where('id', $job->id)->update([
                    'attempts' => 0,
                    'reserved_at' => null,
                ]);

            DB::table('jobs_histories')->where('id', $jobData->history->id)->update(['status' => 0]);
        }

    }
}
