<?php

namespace App\Services;

use App\Support\IdFormatter;
use App\Support\Uuid;

abstract class BaseService
{
    protected function prepareCreateData(array $data, ?string $orgHex, array $binaryFields = []): array
    {
        if (!isset($data['id'])) {
            $data['id'] = Uuid::uuid7Binary();
        }

        $orgBin = IdFormatter::hexToBinary($orgHex);
        if ($orgBin) {
            $data['organization_id'] = $orgBin;
        }

        foreach ($binaryFields as $field) {
            if (!empty($data[$field])) {
                $bin = IdFormatter::hexToBinary($data[$field]);
                if ($bin) {
                    $data[$field] = $bin;
                }
            }
        }

        return $data;
    }

    protected function buildAuditDiff(array $data, $old, array $fieldLabels, ?\Closure $customValueResolver = null): string
    {
        $details = '';
        foreach ($data as $field => $newValue) {
            if (!array_key_exists($field, $fieldLabels)) continue;

            $oldValue = $customValueResolver
                ? $customValueResolver($field, $old)
                : ($old->{$field} ?? '');

            if ($this->normalizeDiffValue($oldValue) !== $this->normalizeDiffValue($newValue)) {
                $details .= $fieldLabels[$field] . ': ' . $oldValue . ' → ' . $newValue . "\n";
            }
        }
        return $details;
    }

    protected function normalizeDiffValue($v): string
    {
        if ($v instanceof \Carbon\Carbon) {
            return $v->toDateString();
        }
        if ($v === null) {
            return '';
        }
        if (is_numeric($v)) {
            return (string) ((float) $v);
        }
        return (string) $v;
    }
}
