<?php

namespace App\Models;

use App\Models\Translations\PostTranslation;
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;

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

    protected $guarded = [];

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

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

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

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