<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class ProductVariant extends Model
{
    protected $fillable = [
        'product_id',
        'sku',
        'price',
        'compare_price',
        'stock_quantity',
        'is_active',
    ];

    protected $casts = [
        'price' => 'decimal:2',
        'compare_price' => 'decimal:2',
        'is_active' => 'boolean',
    ];

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

    public function values(): HasMany
    {
        return $this->hasMany(ProductVariantValue::class);
    }

    public function images(): HasMany
    {
        return $this->hasMany(ProductVariantImage::class)->orderBy('sort_order');
    }

    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    public function isInStock(): bool
    {
        return $this->stock_quantity > 0;
    }

    /**
     * Map of attribute name => value string, e.g. ['Size' => 'Large', 'Color' => 'Red'].
     */
    public function optionMap(): array
    {
        return $this->values
            ->filter(fn (ProductVariantValue $v) => $v->attribute && $v->value)
            ->mapWithKeys(fn (ProductVariantValue $v) => [
                $v->attribute->name => $v->value->value,
            ])
            ->all();
    }

    /**
     * Human readable label, e.g. "Size: Large / Color: Red".
     */
    public function getLabelAttribute(): string
    {
        return collect($this->optionMap())
            ->map(fn ($value, $name) => "{$name}: {$value}")
            ->implode(' / ');
    }

    public function primaryImagePath(): ?string
    {
        return $this->images->first()?->image ?? $this->product?->image;
    }
}
