<?php

namespace App\Modules\Inventory\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;

class Unit extends Model
{
    use HasFactory, LogsActivity;

    protected $fillable = ['name', 'code'];

    public function productsAsBase(): HasMany
    {
        return $this->hasMany(Product::class, 'base_unit_id');
    }

    public function productsAsLarge(): HasMany
    {
        return $this->hasMany(Product::class, 'large_unit_id');
    }

    public function getActivitylogOptions(): LogOptions
    {
        return 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($properties['attributes'])) $resolver($properties['attributes']);
        if (isset($properties['old'])) $resolver($properties['old']);

        $activity->properties = $properties;
    }
}
