<?php

namespace Modules\Slider\Models;

use App\Services\Upload\UploadService;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class Slider extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'type',
        'file_path',
    ];

    protected $casts = [
        'type' => 'string',
    ];

    public function currentDescription(): HasOne
    {
        return $this->hasOne(SliderDescription::class)->where('language_id', config('current_language_id'));
    }

    public function setFilePathAttribute($value): void
    {
        if (! $value) {
            return;
        }

        if (is_string($value)) {
            $this->attributes['file_path'] = $value;
            return;
        }

        $currentType = $this->attributes['type'] ?? $this->type ?? 'image';

        if ($currentType === 'video') {
            $this->attributes['file_path'] = $this->storeVideo($value);
            return;
        }

        $this->attributes['file_path'] = UploadService::upload($value, $this->attributes['file_path'] ?? null, 'sliders/images');
    }

    public function getFileUrlAttribute(): ?string
    {
        return UploadService::url($this->file_path);
    }

    private function storeVideo($file): ?string
    {
        if (! $file) {
            return null;
        }

        $mime = $file->getMimeType();
        if (! str_starts_with($mime, 'video/')) {
            abort(400, ' INVALID FILE ');
        }

        $filename = Str::slug(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME));
        $extension = $file->getClientOriginalExtension();
        $name = $filename . '-' . time() . rand() . '.' . $extension;
        $folder = 'main/sliders/videos';

        $storedPath = $file->storeAs($folder, $name, UploadService::$disk);

        if ($storedPath && ($this->attributes['file_path'] ?? null)) {
            UploadService::delete($this->attributes['file_path']);
        }

        return $storedPath;
    }
}
