<?php

namespace App\Models;

use App\Traits\Multitenantable;
use DateTimeInterface;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Product extends Model
{
    use SoftDeletes, Multitenantable;

    public $primaryKey = 'uuid';

    public $incrementing = false;

    public $keyType = 'string';

    public $imageFields = ['server_image_url'];

    protected $fillable = [
        'uuid',
        'tenant_id',
        'category_id',
        'unit_id',
        'name',
        'server_image_url',
        'has_variant',
        'description'
    ];
    protected $casts = [
        'has_variant' => 'boolean',
        'server_image_url' => 'array',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    protected $dates = ['deleted_at'];

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

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

    public function unit()
    { 
        return $this->belongsTo(Unit::class, 'unit_id');
    }

    public function variants() 
    { 
        return $this->hasMany(ProductVariant::class, 'product_id'); 
    }

    public function likes()
    {
        return $this->hasMany(ProductLike::class, 'product_id');
    }

    public function getServerImageUrlAttribute($value)
    {
        if (!$value) return null;

        $paths = is_array($value) ? $value : json_decode($value, true);

        return collect($paths)->map(function ($path) {
            return asset('storage/' . $path);
        })->toArray();
    }
}
