<?php

namespace App\Domains\Cart\Models;

use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Variant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

#[Fillable([
    'cart_id',
    'catalog_item_id',
    'variant_id',
    'cantidad',
])]
class CartItem extends Model
{
    use HasFactory;

    protected $table = 'carrito_items';

    protected function casts(): array
    {
        return [
            'cart_id' => 'integer',
            'catalog_item_id' => 'integer',
            'variant_id' => 'integer',
            'cantidad' => 'integer',
        ];
    }

    /**
     * @return BelongsTo<Cart, $this>
     */
    public function cart(): BelongsTo
    {
        return $this->belongsTo(Cart::class, 'cart_id');
    }

    /** @return BelongsTo<CatalogItem, $this> */
    public function catalogItem(): BelongsTo
    {
        return $this->belongsTo(CatalogItem::class);
    }

    /** @return BelongsTo<Variant, $this> */
    public function variant(): BelongsTo
    {
        return $this->belongsTo(Variant::class);
    }

    public function selectedItem(): CatalogItem|Variant|null
    {
        return $this->variant ?? $this->catalogItem;
    }
}
