<?php

namespace Kylin\Ecommerce\Models;

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

/**
 * 商品模型
 *
 * 依据《电子商务法》第十七条，商品信息需全面、真实、准确。
 */
class Product extends Model
{
    use SoftDeletes;

    protected $table = 'ecommerce_products';

    protected $fillable = [
        'merchant_id', 'category_id', 'name', 'subtitle', 'sku', 'brand',
        'price', 'original_price', 'cost_price', 'stock', 'min_stock', 'sales',
        'images', 'description', 'specs', 'unit', 'weight',
        'status', 'is_refundable', 'is_new', 'is_hot', 'listed_at',
    ];

    protected $casts = [
        'price' => 'decimal:2',
        'original_price' => 'decimal:2',
        'cost_price' => 'decimal:2',
        'images' => 'array',
        'specs' => 'array',
        'weight' => 'decimal:2',
        'is_refundable' => 'boolean',
        'is_new' => 'boolean',
        'is_hot' => 'boolean',
        'listed_at' => 'datetime',
    ];

    public function merchant(): BelongsTo
    {
        return $this->belongsTo(Merchant::class, 'merchant_id');
    }

    public function category(): BelongsTo
    {
        return $this->belongsTo(Category::class, 'category_id');
    }

    public function specs(): HasMany
    {
        return $this->hasMany(ProductSpec::class, 'product_id');
    }

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