<?php

namespace App\Models;

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

class ItemPhoto extends Model
{
    use HasFactory;

    protected $fillable = [
        'item_id',
        'filename',
        'original_name',
        'path',
        'url',
        'file_size',
        'mime_type',
        'sort_order',
        'is_primary',
    ];

    protected function casts(): array
    {
        return [
            'is_primary' => 'boolean',
        ];
    }

    public function item()
    {
        return $this->belongsTo(Item::class);
    }

    /**
     * Get the full URL for the image, ensuring S3 URLs are properly formatted
     */
    public function getImageUrlAttribute()
    {
        // If URL is already a full URL (starts with http), return as is
        if (filter_var($this->url, FILTER_VALIDATE_URL)) {
            return $this->url;
        }
        
        // Otherwise, generate URL using storage disk
        return Storage::disk('images')->url($this->path);
    }

    /**
     * Override the url accessor to always return the proper URL
     */
    public function getUrlAttribute($value)
    {
        // If stored URL is already a full URL, return it
        if (filter_var($value, FILTER_VALIDATE_URL)) {
            return $value;
        }
        
        // Generate URL from path using the images disk
        return Storage::disk('images')->url($this->path);
    }
}