<?php

namespace MintyPHP\Repository\Support;

final class RepositoryArrayHelper
{
    /**
     * Unwrap a single DB row from its table-name wrapper.
     *
     * MintyPHP DB layer returns rows wrapped in table-name keys, e.g. ['tenants' => [...]].
     * This extracts the inner array for the given table key.
     */
    public static function unwrap(?array $row, string $tableKey): ?array
    {
        if (!$row) {
            return null;
        }

        return $row[$tableKey] ?? null;
    }

    /**
     * Unwrap a list of DB rows from their table-name wrappers.
     */
    public static function unwrapList(mixed $rows, string $tableKey): array
    {
        if (!is_array($rows)) {
            return [];
        }

        $list = [];
        foreach ($rows as $row) {
            $data = $row[$tableKey] ?? null;
            if (is_array($data)) {
                $list[] = $data;
            }
        }

        return $list;
    }

    /**
     * Extract integer IDs from DB rows, unwrapping the table-name key.
     *
     * Returns a deduplicated array of unique positive integer IDs.
     */
    public static function extractIds(mixed $rows, string $tableKey, string $idField = 'id'): array
    {
        if (!is_array($rows)) {
            return [];
        }

        $ids = [];
        foreach ($rows as $row) {
            $data = $row[$tableKey] ?? $row;
            if (is_array($data) && isset($data[$idField])) {
                $ids[] = (int) $data[$idField];
            }
        }

        return array_values(array_unique($ids));
    }

    /**
     * Sanitize an array of IDs to unique positive integers.
     */
    public static function sanitizePositiveIds(array $ids): array
    {
        $ids = array_values(array_unique(array_map('intval', $ids)));

        return array_values(array_filter($ids, static fn (int $id): bool => $id > 0));
    }
}
