<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class ProductVariant extends Model
{
    use HasFactory;

    protected $fillable = [
        'product_id',
        'name',
        'price',
        'is_default',
        'is_active'
    ];

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

    protected static function booted()
    {
        // Ensure only one default variant per product
        static::saving(function ($variant) {
            if ($variant->is_default) {
                static::where('product_id', $variant->product_id)
                    ->where('id', '!=', $variant->id)
                    ->update(['is_default' => false]);
            }
        });

        // Ensure at least one default variant exists
        static::saved(function ($variant) {
            $hasDefault = static::where('product_id', $variant->product_id)
                ->where('is_default', true)
                ->exists();
            
            if (!$hasDefault) {
                $firstVariant = static::where('product_id', $variant->product_id)
                    ->first();
                if ($firstVariant) {
                    $firstVariant->update(['is_default' => true]);
                }
            }
        });
    }

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

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

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