<?php

namespace Daylight\Core\Modules\MediaLibrary\Models;

use Daylight\Core\Modules\MediaLibrary\Models\Pivot\Attachable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphToMany;

class Media extends Model
{
    protected $guarded = [];

    public function attachable(): MorphToMany
    {
        return $this->morphedByMany(Attachable::class, 'attachable')
            ->withPivot('properties', 'order')
            ->using(Attachable::class)
            ->withTimestamps();
    }

    public function getUrl(string $size = 'raw'): string
    {
        if (empty(config('services.bytescale.cdn_url'))) {
            return sprintf('https://upcdn.io/%s/%s%s%s',
                config('services.bytescale.account_id'),
                $size,
                config('services.bytescale.path'),
                $this->handle,
            );
        }

        return sprintf(
            '%s/%s/%s',
            config('services.bytescale.cdn_url'),
            $size,
            str_ireplace(config('services.bytescale.path').'/', '', $this->handle),
        );
    }

    public function scopeVisible(Builder $query): void
    {
        $query->where('visible', 1);
    }
}
