package com.tiedup.remake.v2.furniture;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Wire-format codec for the {@code seatAssignments} map synced to clients
 * via the SEAT_ASSIGNMENTS_SYNC entity data accessor.
 *
 * <p>Format: {@code uuid;seatId|uuid;seatId|…} (empty string = no
 * assignments). Seat ids cannot contain {@code |} or {@code ;} — enforced
 * at parse time in {@link FurnitureParser}.</p>
 */
public final class FurnitureSeatSyncCodec {

    private FurnitureSeatSyncCodec() {}

    /** Serialize an assignments map to its wire form. */
    public static String encode(Map<UUID, String> assignments) {
        if (assignments.isEmpty()) return "";
        StringBuilder sb = new StringBuilder(assignments.size() * 40);
        boolean first = true;
        for (Map.Entry<UUID, String> entry : assignments.entrySet()) {
            if (!first) sb.append('|');
            sb.append(entry.getKey()).append(';').append(entry.getValue());
            first = false;
        }
        return sb.toString();
    }

    /**
     * Parse a wire-form string back into an assignments map. Malformed
     * entries (invalid UUID, missing separator, empty seat id) are skipped
     * silently so a packet from a future protocol version can still be
     * consumed at worst-effort without throwing.
     */
    public static Map<UUID, String> decode(String serialized) {
        Map<UUID, String> result = new LinkedHashMap<>();
        if (serialized == null || serialized.isEmpty()) return result;
        for (String entry : serialized.split("\\|")) {
            int sep = entry.indexOf(';');
            if (sep <= 0 || sep == entry.length() - 1) continue;
            try {
                UUID uuid = UUID.fromString(entry.substring(0, sep));
                String seatId = entry.substring(sep + 1);
                result.put(uuid, seatId);
            } catch (IllegalArgumentException ignored) {
                // Corrupt UUID — skip this entry, preserve the rest.
            }
        }
        return result;
    }
}
