<?php

namespace App\Support;

use App\Models\Organization;

class IdFormatter
{
    public static function hexToBinary(?string $hex): ?string
    {
        if (!$hex) return null;
        try {
            return hex2bin($hex);
        } catch (\Throwable $e) {
            return null;
        }
    }

    public static function formatId($id): ?string
    {
        if ($id === null) return null;
        if (is_string($id) && strlen($id) === 16) {
            return bin2hex($id);
        }
        return (string) $id;
    }

    public static function formatModelId($model, string $field = 'id'): ?string
    {
        if (!$model) return null;
        $raw = $model->getAttributes()[$field] ?? $model->{$field} ?? null;
        return self::formatId($raw);
    }

    public static function normalizeId(string $id): string
    {
        $trimmed = trim($id);
        if (preg_match('/^[a-f0-9]{32}$/i', $trimmed) === 1) {
            $bin = self::hexToBinary($trimmed);
            if ($bin) {
                return $bin;
            }
        }
        return $id;
    }

    public static function findOrganizationByHex(?string $hex): ?Organization
    {
        if (!$hex) return null;
        $bin = self::hexToBinary($hex);
        if (!$bin) return null;
        return Organization::where('id', $bin)->first();
    }
}
