<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class VendorProductImage extends Model
{
    private const DEFAULT_IMAGE_PATH = 'images/default-banner.jpg';

    protected $fillable = [
        'vendor_product_id',
        'image_path',
        'sort_order',
    ];

    public function product()
    {
        return $this->belongsTo(VendorProduct::class, 'vendor_product_id');
    }

    public function getImageUrlAttribute(): ?string
    {
        if (!$this->image_path) {
            return asset(self::DEFAULT_IMAGE_PATH);
        }

        $path = trim((string) $this->image_path);
        if (preg_match('/^https?:\/\//i', $path)) {
            return $path;
        }

        return $this->resolveMediaUrl($path, asset(self::DEFAULT_IMAGE_PATH));
    }

    private function normalizeLegacyMediaPath(string $path): string
    {
        $clean = str_replace('\\', '/', trim($path));
        $clean = preg_replace('#/+#', '/', $clean);

        if (preg_match('#(?:^|/)(images/.*)$#i', $clean, $m)) {
            return ltrim($m[1], '/');
        }

        if (preg_match('#(?:^|/)(storage/.*)$#i', $clean, $m)) {
            return ltrim($m[1], '/');
        }

        return ltrim($clean, '/');
    }

    private function resolveMediaUrl(string $path, string $fallback): string
    {
        $relative = $this->normalizeLegacyMediaPath($path);
        if ($relative === '') {
            return $fallback;
        }

        return $this->assetWithVersion($relative);
    }

    private function assetWithVersion(string $relative): string
    {
        $url = asset($relative);
        $mtime = $this->updated_at?->getTimestamp();
        if (!$mtime) {
            return $url;
        }
        return $url . '?v=' . $mtime;
    }
}
