<?php

namespace WPSN\Modules\Audit;

defined('ABSPATH') || exit;

/**
 * Shapes duplicate-key DB rows into stable groups for finalize-time issue building.
 */
final class AuditDuplicateKeyGroups
{
    /**
     * @param array<int,array<string,mixed>> $rows
     * @return array<int,array{object_type:string,key:string,rows:array<int,array{object_id:int,object_subtype:string}>}>
     */
    public static function build(array $rows, string $keyField): array
    {
        $keyField = (string) $keyField;
        if ($keyField === '' || empty($rows)) {
            return [];
        }

        $groups = [];
        foreach ($rows as $row) {
            if (!is_array($row)) {
                continue;
            }

            $objectType = isset($row['object_type']) ? sanitize_key((string) $row['object_type']) : '';
            $objectId = isset($row['object_id']) ? (int) $row['object_id'] : 0;
            $objectSubtype = isset($row['object_subtype']) ? sanitize_key((string) $row['object_subtype']) : '';
            $key = isset($row[$keyField]) ? (string) $row[$keyField] : '';

            if ($objectType === '' || $objectId <= 0 || $key === '') {
                continue;
            }

            $bucket = $objectType . "\n" . $key;
            if (!isset($groups[$bucket])) {
                $groups[$bucket] = [
                    'object_type' => $objectType,
                    'key' => $key,
                    'rows' => [],
                ];
            }

            $groups[$bucket]['rows'][] = [
                'object_id' => $objectId,
                'object_subtype' => $objectSubtype,
            ];
        }

        return array_values($groups);
    }
}
