<?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 TriggerFlowOnCreatePostEvent implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    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', 'created')
            ->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;

                // dd($flow->toArray());

                if (! $operation) {
                    continue;
                }

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

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

                // dd('done', $operation, $flowLog);
            }
        }
    }
}
