<?php

namespace Daylight\Core\Modules\MediaLibrary\Models\Concerns;

use Daylight\Core\Modules\MediaLibrary\DefaultMedia;
use Daylight\Core\Modules\MediaLibrary\Models\Media;
use Daylight\Core\Modules\MediaLibrary\Models\Pivot\Attachable;
use Illuminate\Database\Eloquent\Relations\MorphToMany;
use Illuminate\Support\Collection;

trait InteractsWithMedia
{
    public function media(): MorphToMany
    {
        return $this->morphToMany(Media::class, 'attachable')
            ->withPivot('properties', 'order')
            ->using(Attachable::class)
            ->orderBy('order')
            ->withTimestamps();
    }

    public function getMedia(?string $field = null): Collection
    {
        $this->loadMissing('media');

        return $this->media->where('pivot.properties.field', $field);
    }

    public function getFirstMedia(?string $field = null)
    {
        return $this->getMedia($field)->first() ?? DefaultMedia::make();
    }
}
