<?php

namespace Aura\Flows\Jobs;

use Aura\Flows\Resources\Flow;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class TriggerFlowOnDeletedPostEvent implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    // We can not use SerializesModels here, because we need to pass the Post object to the Job, and the Post object is not serializable (because it is deleted)
    // use SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(public $resource)
    {
        //
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        // Is there a Flow with 'trigger' == 'resource' and 'options.resource' == 'Post' and 'options.event' == 'created'
        // If so, run the Flow

        // dump($this->resource->type);

        $flows = Flow::where('trigger', 'resource')
            ->where('options->resource', get_class($this->resource))
            ->where('options->event', 'deleted')
            ->get();

        // dump(Flow::get());

        if ($flows && $flows->count() > 0) {
            // Trigger the Flow
            // get the Flow's Operation
            // Run the Operation
            foreach ($flows as $flow) {
                // Get the Operation
                $operation = $flow->operation;

                // Create a Flow Log
                $flowLog = $flow->logs()->create([
                    'post_id' => $this->resource->id,
                    'status' => 'running',
                ]);

                // Run the Operation
                $operation->run($this->resource, $flowLog->id);
            }
        }
    }
}
