<?php

namespace Daylight\Core\Models;

use Daylight\Core\Models\Enums\PublishStatus;
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\BelongsTo;
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 = [];

    protected function casts(): array
    {
        return [
            'status' => PublishStatus::class,
        ];
    }

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

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

    public function page(): BelongsTo
    {
        return $this->belongsTo(daylightModel('page'));
    }

    public function products(): HasMany
    {
        return $this->hasMany(daylightModel('product'));
    }

    public function translations(): HasMany
    {
        return $this->hasMany(daylightModel('brand_translation'));
    }

    public function defaultTranslation(): HasOne
    {
        return $this->hasOne(daylightModel('brand_translation'))
            ->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();
    }
}
