<?php

namespace Modules\News\Models;

use App\Services\Upload\UploadService;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\SoftDeletes;

class News extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'image',
    ];

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

    public function setImageAttribute($value): void
    {
        if ($value) {
            if (is_string($value)) {
                $this->attributes['image'] = $value;
            } else {
                $image = UploadService::upload($value, $this->image ?? null, 'news');
                $this->attributes['image'] = $image;
            }
        } elseif ($this->image ?? false) {
            $this->attributes['image'] = $this->image;
        }
    }

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