<?php

namespace App\Jobs\Ecommerce\Product;

use App\Models\Ecommerce\Product\Property\ProductAttributeValue;
use App\Models\Ecommerce\Product\Property\ProductProperty;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;

class UpdateProductRelations implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     */
    public function __construct(
        public mixed $user,
        public mixed $model,
        public array|string|null $categories = [],
        public array|string|null $collections = [],
        public array|string|null $channel = [],
        public array|string|null $properties = [],
        public array|string|null $inventories = [],
    ) {
        //
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        $this->model::withoutEvents(function () {
            $this->model->categories()->sync($this->categories);
            $this->model->collections()->sync($this->collections);
            $this->model->inventories()->sync($this->inventories);

            if ($this->user->isAdmin()) {
                $this->model->channels()->sync($this->channel);
            }

            $attribute_ids = $this->properties
                                ? DB::table('attributes')->whereIn('slug', array_keys($this->properties))->get(['id', 'type', 'slug'])
                                : collect();

            $attribute_ids->each(function ($attribute) {
                $productAttribute = ProductProperty::updateOrCreate([
                    'product_id' => $this->model->id,
                    'attribute_id' => $attribute->id,
                ]);

                ProductAttributeValue::updateOrCreate(['product_attribute_id' => $productAttribute->id], [
                    'attribute_value_id' => in_array($attribute->type, ['text', 'number']) ? null : $this->properties[$attribute->slug],
                    'product_custom_value' => in_array($attribute->type, ['text', 'number']) ? $this->properties[$attribute->slug] : null,
                ]);
            });

            // sync properties json
            if (method_exists($this->model, 'syncPropertiesJson')) {
                $this->model->syncPropertiesJson();
            }
        });
    }
}
