<?php

namespace OtomaticAi\Jobs;

use ActionScheduler_Store;
use OtomaticAi\Models\Publication;
use OtomaticAi\Utils\Scheduler;
use OtomaticAi\Vendors\Carbon\Carbon;

class CheckPublicationsJob extends Job
{

    /**
     * Create a new job instance.
     */
    public function __construct() {}

    /**
     * Execute the job.
     */
    public function handle()
    {
        // verify if a publish_publication action is already scheduled
        $actions = Scheduler::get("publish_publication", null, [
            "status" => ActionScheduler_Store::STATUS_PENDING,
        ]);

        if (!empty($actions)) {
            return;
        }

        $publication = Publication::idle()
            ->whereRelation('project', 'enabled', true)
            ->where("published_at", "<=", Carbon::now())
            ->where("status", "idle")
            ->orderBy("published_at", "asc")
            ->orderBy("id", "asc")
            ->first();

        if (!$publication) {
            return;
        }

        // verify if a publish_publication action is already scheduled for this publication
        $actions = Scheduler::get("publish_publication", [$publication->id], [
            "status" => ActionScheduler_Store::STATUS_PENDING,
        ]);

        if (!empty($actions)) {
            return;
        }

        Scheduler::single("publish_publication", [$publication->id]);
    }
}
