/* © SRSoftware 2025 */
package de.srsoftware.umbrella.core.model;

import static de.srsoftware.umbrella.core.constants.Field.*;
import static de.srsoftware.umbrella.core.constants.Text.STRING;
import static de.srsoftware.umbrella.core.exceptions.UmbrellaException.*;
import static de.srsoftware.umbrella.core.model.Translatable.t;

import de.srsoftware.umbrella.core.exceptions.UmbrellaException;
import java.util.Arrays;
import java.util.Base64;
import java.util.Objects;
import java.util.Set;
import org.json.JSONObject;

public record Attachment(String name, String mime, byte[] content) {

	private static final Base64.Decoder BASE64 = Base64.getDecoder();

	@Override
	public boolean equals(Object o) {
		if (!(o instanceof Attachment that)) return false;
		return Objects.equals(name, that.name) && Objects.equals(mime, that.mime) && Objects.deepEquals(content, that.content);
	}

	@Override
	public int hashCode() {
		return Objects.hash(name, mime, Arrays.hashCode(content));
	}

	public static <T> Attachment of(JSONObject json) throws UmbrellaException {
		for (var key : Set.of(NAME, MIME, DATA)) {
			if (!json.has(key)) throw missingField(key);
		}
		if (!(json.get(NAME) instanceof String name)) throw invalidField(NAME,t(STRING));
		if (!(json.get(MIME) instanceof String mime)) throw invalidField(MIME,t(STRING));
		if (!(json.get(DATA) instanceof String data)) throw invalidField(DATA,t(STRING));
		return new Attachment(name,mime, BASE64.decode(data));
	}
}
