<?php

namespace Daylight\Core\Models;

use Daylight\Core\Modules\Multilingualism\Contracts\HasTranslations;
use Daylight\Core\Modules\Multilingualism\Models\Concerns\InteractsWithTranslations;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;

class Attribute extends Model implements HasTranslations
{
    use InteractsWithTranslations;

    protected $guarded = [];

    protected $casts = [
        'filterable' => 'boolean',
    ];

    protected static function boot(): void
    {
        parent::boot();

        static::addGlobalScope('order', function (Builder $builder) {
            $builder->orderBy('order');
        });
    }

    public function translatedFields(): array
    {
        return ['name'];
    }

    public function categories(): BelongsToMany
    {
        return $this->belongsToMany(daylightModel('category'));
    }

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

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

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