/* © SRSoftware 2025 */
package de.srsoftware.umbrella.messagebus.events;

import static de.srsoftware.umbrella.core.ModuleRegistry.accountingService;
import static de.srsoftware.umbrella.core.constants.Field.*;
import static de.srsoftware.umbrella.core.model.Translatable.t;

import de.srsoftware.umbrella.core.constants.Field;
import de.srsoftware.umbrella.core.constants.Module;
import de.srsoftware.umbrella.core.constants.Text;
import de.srsoftware.umbrella.core.model.Transaction;
import de.srsoftware.umbrella.core.model.Translatable;
import de.srsoftware.umbrella.core.model.UmbrellaUser;
import java.util.Collection;
import java.util.Map;

public class TransactionEvent extends Event<Transaction> {
	private Collection<UmbrellaUser> audience;

	public TransactionEvent(UmbrellaUser initiator, Transaction transaction, EventType type) {
		super(initiator, Module.ACCOUNTING, transaction, type);
		audience = null;
	}

	public TransactionEvent(UmbrellaUser initiator, Transaction transaction, Map<String, Object> oldData){
		super(initiator,Module.ACCOUNTING,transaction,oldData);
	}


	@Override
	public Collection<UmbrellaUser> audience() {
		if (audience == null) audience = accountingService().loadAccount(payload().accountId()).userMap().values();
		return audience;
	}

	@Override
	public Translatable describe() {
		var user   = initiator().name();
		var type   = t(Text.TRANSACTION);
		var entity = payload().purpose();
		return switch (eventType()){
			case CREATE -> describeDetail();
			case DELETE -> describeDetail();
			case UPDATE -> describeUpdate();
			case null, default -> t("TODO"); // TODO
		};
	}

	private Translatable describeUpdate() {
		var head = t("Changes in {type} '{entity}':\n\n{body}",Field.TYPE,t(Text.TRANSACTION),Field.ENTITY,oldData().get(PURPOSE),BODY,diff().orElse(""));
		return t("{head}\n\n{link}","head",head,"link",link());
	}

	private Translatable describeDetail(){
		var tr = payload();

		var message = "{source}: {source_name}\n{destination}: {dest_name}\n{amount}: {value}\n{purpose}: {purpose_val}\n\n{link}";
		return t(message,SOURCE,t(Text.SOURCE), "source_name",tr.source(), DESTINATION,t(Text.DESTINATION),"dest_name",tr.destination(), AMOUNT,t(Text.AMOUNT), VALUE,tr.amount(), PURPOSE,t(Text.PURPOSE),"purpose_val",tr.purpose(),"link",link());
	}

	private Translatable link() {
		return t("You can view/edit this transaction at {base_url}/account/{id}", ID, payload().accountId());
	}

	@Override
	public Translatable subject() {
		var user   = initiator().name();
		var entity = payload().purpose();
		return switch (eventType()){
			case CREATE -> t("{user} added a new transaction: {entity}", USER,user, ENTITY, entity);
			case DELETE -> t("The transaction '{entity}' has been deleted by {user}",Field.ENTITY, entity, USER, user);
			case UPDATE -> t("{user} updated the transaction '{entity}'", USER,user, ENTITY, oldData().get(PURPOSE));
			case null, default -> t("TODO"); // TODO
		};
	}
}
