<?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;

/**
 * 订单模型
 *
 * 依据《电子商务法》第四十九条，订单生成即合同成立。
 * 依据《消费者权益保护法》第二十五条，支持 7 天无理由退货。
 */
class Order extends Model
{
    use SoftDeletes;

    protected $table = 'ecommerce_orders';

    protected $fillable = [
        'order_no', 'user_id', 'merchant_id', 'status',
        'total_amount', 'discount_amount', 'freight_amount', 'pay_amount',
        'coupon_code', 'coupon_id', 'payment_method', 'transaction_id',
        'paid_at', 'shipped_at', 'delivered_at', 'completed_at',
        'cancelled_at', 'cancel_reason', 'remark', 'buyer_ip',
    ];

    protected $casts = [
        'total_amount' => 'decimal:2',
        'discount_amount' => 'decimal:2',
        'freight_amount' => 'decimal:2',
        'pay_amount' => 'decimal:2',
        'paid_at' => 'datetime',
        'shipped_at' => 'datetime',
        'delivered_at' => 'datetime',
        'completed_at' => 'datetime',
        'cancelled_at' => 'datetime',
    ];

    public function user(): BelongsTo
    {
        return $this->belongsTo(\App\Models\User::class);
    }

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

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

    public function address(): BelongsTo
    {
        return $this->belongsTo(OrderAddress::class, 'id', 'order_id');
    }

    public function refund(): HasMany
    {
        return $this->hasMany(Refund::class, 'order_id');
    }

    public function contract(): BelongsTo
    {
        return $this->belongsTo(Contract::class, 'id', 'order_id');
    }
}