<?php

namespace Modules\Team\Models;

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

class Team extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'image',
    ];

    /**
     * Get current description for the team member.
     */
    public function currentDescription(): HasOne
    {
        return $this->hasOne(TeamDescription::class)->where('language_id', config('current_language_id'));
    }

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

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

