<?php

namespace App\Models;

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

#[Fillable(['product_id', 'name', 'value', 'price', 'purchase_price', 'stock', 'is_active'])]
class ProductVariant extends Model
{
    protected function casts(): array
    {
        return [
            'price' => 'decimal:2',
            'purchase_price' => 'decimal:2',
            'is_active' => 'boolean',
        ];
    }

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

    public function label(): string
    {
        return "{$this->name}: {$this->value}";
    }

    public function inventoryMovements(): HasMany
    {
        return $this->hasMany(InventoryMovement::class)->latest();
    }

    public function effectivePrice(): float
    {
        return $this->product->sellingPrice($this->basePrice());
    }

    public function basePrice(): float
    {
        return (float) ($this->price ?? $this->product->price);
    }

    public function compareAtPrice(): ?float
    {
        return $this->product->compareAtPrice($this->basePrice());
    }
}
