<?php

namespace Daylight\Core\Models;

use Daylight\Core\Models\Translations\BrandTranslation;
use Daylight\Core\Modules\MediaLibrary\Contracts\HasMedia;
use Daylight\Core\Modules\MediaLibrary\Models\Concerns\InteractsWithMedia;
use Daylight\Core\Modules\MediaLibrary\Models\Media;
use Daylight\Core\Modules\MediaLibrary\Models\Pivot\Attachable;
use Daylight\Core\Modules\Multilingualism\Contracts\HasTranslations;
use Daylight\Core\Modules\Multilingualism\Models\Concerns\InteractsWithTranslations;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\MorphToMany;
use Spatie\Sluggable\HasSlug;
use Spatie\Sluggable\SlugOptions;

class Brand extends Model implements HasMedia, HasTranslations
{
    use HasSlug;
    use InteractsWithMedia;
    use InteractsWithTranslations;

    protected $guarded = [];

    public function getSlugOptions(): SlugOptions
    {
        return SlugOptions::create()
            ->generateSlugsFrom('name')
            ->saveSlugsTo('slug');
    }

    public function translatedFields(): array
    {
        return ['meta_title', 'meta_description', 'robots'];
    }

    public function products(): HasMany
    {
        return $this->hasMany(Product::class);
    }

    public function translations(): HasMany
    {
        return $this->hasMany(BrandTranslation::class);
    }

    public function defaultTranslation(): HasOne
    {
        return $this->hasOne(BrandTranslation::class)
            ->where('locale', config('multilingualism.default_locale'));
    }

    public function gallery(): MorphToMany
    {
        return $this->morphToMany(Media::class, 'attachable')
            ->withPivot('properties', 'order')
            ->whereJsonContains('attachables.properties->field', 'gallery')
            ->using(Attachable::class)
            ->orderBy('order')
            ->withTimestamps();
    }
}
