<?php

namespace App\Modules\Inventory\Support;

use App\Models\User;
use App\Modules\Admin\ActivityLog\DTOs\ActivityLogWriteData;
use App\Modules\Admin\ActivityLog\Services\ActivityLogService;
use Illuminate\Database\Eloquent\Model;

final class InventoryCatalogActivityLog
{
    public static function record(Model $model, string $action): void
    {
        $tenantId = (int) $model->getAttribute('tenant_id');
        if ($tenantId === 0) {
            return;
        }

        $user = auth()->user();
        $userId = $user instanceof User ? (int) $user->id : null;

        $name = self::displayName($model);
        $label = class_basename($model).' #'.$model->getKey();

        $description = (string) __(
            'activity_logs.inventory.entity_'.$action,
            ['label' => $label, 'name' => $name],
        );

        app(ActivityLogService::class)->log(new ActivityLogWriteData(
            tenantId: $tenantId,
            userId: $userId,
            module: 'inventory',
            action: $action,
            entityType: $model::class,
            entityId: $model->getKey(),
            description: $description,
        ));
    }

    private static function displayName(Model $model): string
    {
        $currency = $model->getAttribute('currency');
        $amount = $model->getAttribute('amount');
        if ($currency !== null && $amount !== null) {
            return (string) $currency.' '.$amount;
        }

        return (string) ($model->getAttribute('name')
            ?? $model->getAttribute('sku')
            ?? $model->getAttribute('code')
            ?? '');
    }
}
