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

import static de.srsoftware.tools.Optionals.isSet;
import static de.srsoftware.umbrella.core.constants.Constants.JSONOBJECT;
import static de.srsoftware.umbrella.core.constants.Field.*;
import static de.srsoftware.umbrella.core.constants.Field.ATTACHMENTS;
import static de.srsoftware.umbrella.core.constants.Text.STRING;
import static de.srsoftware.umbrella.core.exceptions.UmbrellaException.invalidField;
import static de.srsoftware.umbrella.core.exceptions.UmbrellaException.missingField;
import static de.srsoftware.umbrella.core.model.Translatable.t;

import de.srsoftware.umbrella.core.exceptions.UmbrellaException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import org.json.JSONArray;
import org.json.JSONObject;

public class TranslatedMessage extends Message<String> {
	public TranslatedMessage(UmbrellaUser sender, String subject, String body, Collection<Attachment> attachments) {
		super(sender, subject, body, attachments);
	}

	public static TranslatedMessage from(JSONObject json) throws UmbrellaException {
		for (var key : Set.of(SENDER, SUBJECT, BODY)) {
			if (!json.has(key)) throw missingField(key);
		}
		if (!(json.get(SENDER) instanceof JSONObject senderObject)) throw invalidField(SENDER, t(JSONOBJECT));
		if (!(json.get(SUBJECT) instanceof String subject && isSet(subject))) throw invalidField(SUBJECT,t(STRING));
		if (!(json.get(BODY) instanceof String body && isSet(body))) throw invalidField(BODY,t(STRING));

		var user = UmbrellaUser.of(senderObject);
		if (!(user instanceof UmbrellaUser sender)) throw new UmbrellaException(400, t("Sender is not an umbrella user!"));
		var attachments = new ArrayList<Attachment>();
		if (json.has(ATTACHMENTS)){
			var jsonAttachments = json.get(ATTACHMENTS);
			if (jsonAttachments instanceof JSONObject obj) jsonAttachments = new JSONArray(List.of(obj));
			if (jsonAttachments instanceof JSONArray arr){
				for (var att : arr){
					if (!(att instanceof JSONObject o)) throw new UmbrellaException(400, t("Attachments contains entry that is not an object: {entry}","entry",att));
					var attachment = Attachment.of(o);
					attachments.add(attachment);
				}
			}
		}
		return new TranslatedMessage(sender,subject,body,attachments);
	}
}
