<?php

namespace App\Models;

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

class ProductImage extends Model
{
    protected $fillable = [
        'product_id',
        'path',
        'optimized_path',
        'is_primary',
        'sort_order',
    ];

    protected $casts = [
        'is_primary' => 'boolean',
    ];

    protected $appends = ['url', 'optimized_url'];

    public function product()
    {
        return $this->belongsTo(Product::class);
    }

    public function getUrlAttribute(): string
    {
        if (!$this->path) {
            return '';
        }
        
        // If path is already a full URL, return it
        if (str_starts_with($this->path, 'http')) {
            return $this->path;
        }
        
        // Return relative path so frontend proxy can handle it
        return '/storage/' . $this->path;
    }

    public function getOptimizedUrlAttribute(): string
    {
        $path = $this->optimized_path ?? $this->path;
        
        if (!$path) {
            return '';
        }
        
        // If path is already a full URL, return it
        if (str_starts_with($path, 'http')) {
            return $path;
        }
        
        // Return relative path so frontend proxy can handle it
        return '/storage/' . $path;
    }
}
