<?php

namespace App\Models;

use App\Traits\Multitenantable;
use DateTimeInterface;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class OrderItem extends Model
{
    use Multitenantable;

    protected $primaryKey = 'uuid';
    public $incrementing = false;
    protected $keyType = 'string';

    protected $fillable = [
        'uuid', 
        'tenant_id', 
        'order_id', 
        'product_variant_id', 
        'quantity',
        'product_image_url_snapshot', 
        'product_name_snapshot',
        'product_variant_name_snapshot', 
        'selling_price_snapshot', 
        'subtotal'
    ];

    protected $casts = [
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    public function order(): BelongsTo 
    { 
        return $this->belongsTo(Order::class, 'order_id', 'uuid'); 
    }
    public function variant(): BelongsTo 
    { 
        return $this->belongsTo(ProductVariant::class, 'product_variant_id', 'uuid'); 
    }

    public function getProductImageUrlSnapshotAttribute($value)
    {
        if (!$value) return null;
        
        return asset('storage/' . $value);
    }
}
