<?php

namespace Mtc\Plugins\MtcUnioIntegration\Classes;

use Illuminate\Database\Eloquent\Model;

class QueueMessage extends Model
{
    const STATUS_PENDING = 'pending';
    const STATUS_PROCESSING = 'processing';
    const STATUS_SUCCESS = 'success';
    const STATUS_FAILED = 'failed';

    public function saveStatus(string $status) : void
    {
        $this->status = $status;
        $this->save();
    }


    public function scopePending($query)
    {
        return $query->where('status', QueueMessage::STATUS_PENDING);
    }


    public static function enqueue($entity_type, $entity_id)
    {
        $existing_pending_message = static::query()
            ->where('entity_type', $entity_type)
            ->where('entity_id', $entity_id)
            ->where('status', QueueMessage::STATUS_PENDING)
            ->first()
        ;

        if (! $existing_pending_message) {
            $msg = new static();

            $msg->entity_type = $entity_type;
            $msg->entity_id = $entity_id;
            $msg->save();
        }
    }


    public static function dequeue($is_dry_run = false)
    {
        $grace_period_seconds = 10;

        $msg = static::query()
            ->pending()
            ->whereRaw('UNIX_TIMESTAMP() - UNIX_TIMESTAMP(created_at) > ?', [ $grace_period_seconds ])
            ->orderBy('created_at')
            ->first()
        ;

        if ($msg && ! $is_dry_run) {
            $msg->saveStatus(QueueMessage::STATUS_PROCESSING);
        }

        return $msg;
    }

}
