<?php

namespace App\Modules\Inventory\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;


class Warehouse extends Model
{
    /** @use HasFactory<\Database\Factories\WarehouseFactory> */
    use HasFactory;
    use \Spatie\Activitylog\Traits\LogsActivity;

    protected $fillable = [
        'code',
        'name',
        'type',
        'address',
        'description',
        'license_plate',
        'driver_name',
        'default_transit_warehouse_id',
    ];

    protected $casts = [
        'type' => \App\Enums\WarehouseType::class,
    ];

    public function getActivitylogOptions(): \Spatie\Activitylog\LogOptions
    {
        return \Spatie\Activitylog\LogOptions::defaults()
            ->logAll()
            ->logOnlyDirty()
            ->dontSubmitEmptyLogs();
    }

    public function tapActivity(\Spatie\Activitylog\Contracts\Activity $activity, string $eventName)
    {
        $properties = $activity->properties instanceof \Illuminate\Support\Collection 
            ? $activity->properties->toArray() 
            : $activity->properties;
        
        $snapshot = $properties['snapshot'] ?? [];
        $snapshot['name'] = $this->name;
        $properties['snapshot'] = $snapshot;

        $resolver = function (&$data) {
            if (empty($data) || !is_array($data)) return;
            
            foreach (['created_by', 'updated_by'] as $f) {
                if (isset($data[$f]) && is_numeric($data[$f])) {
                    $data[$f] = \App\Modules\Core\Models\User::find($data[$f])?->name;
                }
            }

            if (isset($data['default_transit_warehouse_id']) && is_numeric($data['default_transit_warehouse_id'])) {
                $data['default_transit_warehouse_id'] = self::find($data['default_transit_warehouse_id'])?->name;
            }
        };

        if (isset($properties['attributes'])) $resolver($properties['attributes']);
        if (isset($properties['old'])) $resolver($properties['old']);

        $activity->properties = $properties;
    }

    public function inventories(): \Illuminate\Database\Eloquent\Relations\HasMany
    {
        return $this->hasMany(Inventory::class);
    }

    /**
     * 預設在途倉庫
     */
    public function defaultTransitWarehouse(): \Illuminate\Database\Eloquent\Relations\BelongsTo
    {
        return $this->belongsTo(self::class, 'default_transit_warehouse_id');
    }

    public function products(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
    {
        return $this->belongsToMany(Product::class, 'inventories')
            ->withPivot(['quantity', 'safety_stock', 'location'])
            ->withTimestamps();
    }
}
