<?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\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphToMany;
use Illuminate\Support\Facades\Storage;

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

    protected $with = [
        'conversions',
    ];

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

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

    public function getUrl(string $conversion = 'raw'): string
    {
        if ($conversion === 'raw') {
            // Return original file
            if ($this->path && $this->disk) {
                return Storage::disk($this->disk)->url($this->path);
            }

            return '';
        }

        // Check if conversion exists
        $conversionRecord = $this->conversions()->where('name', $conversion)->first();

        if ($conversionRecord) {
            return $conversionRecord->getUrl();
        }

        // Fallback to original file
        return $this->getUrl('raw');
    }

    public function getPath(): string
    {
        return $this->path ?? $this->handle ?? '';
    }

    public function isImage(): bool
    {
        return str_starts_with($this->type ?? '', 'image/') && $this->type !== 'image/svg+xml';
    }

    public function isVideo(): bool
    {
        return str_starts_with($this->type ?? '', 'video/');
    }

    public function isPdf(): bool
    {
        return $this->type === 'application/pdf';
    }

    public function isDocument(): bool
    {
        return in_array($this->type, [
            'application/msword',
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            'application/vnd.ms-excel',
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        ]);
    }

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