<?php

namespace App\Modules\Inventory\Models;

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


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

    protected $fillable = [
        'inventory_id',
        'type',
        'quantity',
        'unit_cost',
        'balance_before',
        'balance_after',
        'reason',
        'reference_type',
        'reference_id',
        'user_id',
        'actual_time',
    ];

    protected $casts = [
        // actual_time 不做時區轉換，保留原始字串格式（台北時間）
        // 原因：資料庫儲存的是台北時間，但 MySQL 時區為 UTC
        // 若使用 datetime cast，Laravel 會誤當作 UTC 再轉回台北時間，造成偏移
        'unit_cost' => 'decimal:4',
    ];

    public function inventory(): \Illuminate\Database\Eloquent\Relations\BelongsTo
    {
        return $this->belongsTo(Inventory::class);
    }

    public function reference(): \Illuminate\Database\Eloquent\Relations\MorphTo
    {
        return $this->morphTo();
    }

    public function getActivitylogOptions(): \Spatie\Activitylog\LogOptions
    {
        return \Spatie\Activitylog\LogOptions::defaults()
            ->logAll()
            ->dontLogIfAttributesChangedOnly(['updated_at'])
            // 取消 logOnlyDirty，代表新增時(created)也要留紀錄
            ->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'] ?? [];

        // 試著取得商品與倉庫名稱來作為主要顯示依據
        $inventory = $this->inventory;
        if ($inventory) {
            $snapshot['warehouse_name'] = $inventory->warehouse ? $inventory->warehouse->name : null;
            $snapshot['product_name'] = $inventory->product ? $inventory->product->name : null;
            $snapshot['batch_number'] = $inventory->batch_number;
        }

        // 把異動類型與數量也拉到 snapshot
        $snapshot['type'] = $this->type;
        $snapshot['quantity'] = $this->quantity;
        $snapshot['reason'] = $this->reason;
        
        // 替換使用者名稱
        $resolver = function (&$data) {
            if (empty($data) || !is_array($data)) return;
            if (isset($data['user_id']) && is_numeric($data['user_id'])) {
                $data['user_id'] = \App\Modules\Core\Models\User::find($data['user_id'])?->name;
            }
        };

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

        $properties['snapshot'] = $snapshot;
        $activity->properties = $properties;
    }
}
