<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class File extends Model
{
    use HasFactory;

    protected $fillable = [
        'fileable_type',
        'fileable_id',
        'type',
        'name',
        'extension',
        'path',
    ];

    public $appends = [
        'url'
    ];

    public static $file_directories = [
        'import-temp' => 'import-temp/',
        'avatar' => 'user-avatar/',
        'dataDiri' => 'data-diri/'
    ];

    public function fileable()
    {
        return $this->morphTo();
    }

    public static function getDirectory($type)
    {
        return self::$file_directories[$type] ?? 'any';
    }

    public static function getFileName($type, $id)
    {
        return $type . '-' . $id . '-' . Str::random(10);
    }

    public function getUrlAttribute()
    {
        return url(Storage::url($this->path));
    }

    public static function storeFile($type, $id, $file)
    {
        $fileName = self::getFileName($type, $id);
        $directory = self::getDirectory($type);
        $extension = $file->getClientOriginalExtension();
        $path = $directory . $fileName . '.' . $extension;
        $file->storeAs('public/' . $directory, $fileName . '.' . $extension);
        return $path;
    }
}
