<?php

namespace App\Models;

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

class CartItem extends Model
{
    protected $fillable = [
        'cart_id',
        'product_id',
        'product_variant_id',
        'quantity',
    ];

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

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

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

    /**
     * Unit price for this line — the variant's price when a variant is selected,
     * otherwise the base product price.
     */
    public function unitPrice(): float
    {
        if ($this->product_variant_id && $this->productVariant) {
            return (float) $this->productVariant->price;
        }

        return (float) $this->product->price;
    }

    /**
     * Stock available for what this line actually represents.
     */
    public function availableStock(): int
    {
        if ($this->product_variant_id && $this->productVariant) {
            return (int) $this->productVariant->stock_quantity;
        }

        return (int) $this->product->stock_quantity;
    }

    public function isPurchasable(): bool
    {
        if (! $this->product || ! $this->product->is_active) {
            return false;
        }

        if ($this->product_variant_id) {
            return $this->productVariant
                && $this->productVariant->is_active
                && $this->productVariant->stock_quantity >= $this->quantity;
        }

        return $this->product->stock_quantity >= $this->quantity;
    }

    public function imageUrl(): ?string
    {
        $path = $this->productVariant?->images->first()?->image ?? $this->product->image;

        return $path ? asset('storage/'.$path) : null;
    }

    public function variantLabel(): ?string
    {
        return $this->productVariant?->label;
    }

    public function getLineTotalAttribute(): float
    {
        return $this->quantity * $this->unitPrice();
    }
}
