<?php

namespace App\Models;

use App\Models\Objects\Field;
use App\Models\Objects\Values\RelationValue;
use App\Support\RelationValuesTrait;
use App\Support\UuidScopeTrait;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Asset extends Model {
    use UuidScopeTrait, HasFactory, RelationValuesTrait;

    protected $guarded = ['id'];

    public function user(): BelongsTo {
        return $this->belongsTo(User::class);
    }


    public function getIsImageAttribute(): bool {
        return $this->type === 'image';
    }


    public function links(): array {
        return [
            'open' => asset("/api/assets/{$this->uuid}"),
            'download' => asset("/api/assets/{$this->uuid}/download"),
            'direct' => asset("storage/{$this->path}"),
            'full' => $this->isImage ? asset("/api/assets/{$this->uuid}/render") : null,
            'thumb' => $this->isImage ? asset("/api/assets/{$this->uuid}/render?width=300") : null
        ];
    }

    public function coordinates(): array {
        return ['latitude' => $this->latitude, 'longitude' => $this->longitude, 'accuracy' => $this->accuracy];
    }

    public function saveValue($fieldName, $object) {
        $field = Field::byUuidOrName($fieldName)->first();
        $relationValue = RelationValue::create();
        $relationValue->set($this);
        $relationValue->update([
            'field_id' => $field->id,
            'object_id' => $object->id,
        ]);
    }
}
