<?php

namespace App\Models;

use App\Enums\Status;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;

class ProductVariant extends Model
{
    use HasFactory;

    protected $fillable = [
        'product_id',
        'color_id',
        'size_id',
        'sku',
        'barcode',
        'price_override',
        'status',
    ];

    protected function casts(): array
    {
        return [
            'status' => Status::class,
            'price_override' => 'decimal:2',
        ];
    }

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

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

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

    public function inventory(): HasOne
    {
        return $this->hasOne(Inventory::class);
    }

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

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

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

    /** The effective selling price: variant surcharge/override, else the product's current price. */
    protected function price(): Attribute
    {
        return Attribute::get(fn () => $this->price_override !== null
            ? (float) $this->price_override
            : (float) $this->product->current_price
        );
    }

    /** "Maroon / L" style label for cart lines and receipts. */
    protected function label(): Attribute
    {
        return Attribute::get(function () {
            $parts = array_filter([$this->color?->name, $this->size?->name]);

            return $parts ? implode(' / ', $parts) : null;
        });
    }

    public function scopeActive(Builder $query): void
    {
        $query->where('status', Status::Active);
    }
}
