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

import static de.srsoftware.umbrella.core.constants.Field.*;
import static de.srsoftware.umbrella.core.constants.Module.WIKI;
import static de.srsoftware.umbrella.core.model.Translatable.t;
import static de.srsoftware.umbrella.messagebus.events.Event.EventType.MEMBER_ADDED;

import de.srsoftware.umbrella.core.constants.Field;
import de.srsoftware.umbrella.core.model.*;
import java.util.Collection;
import java.util.Map;


public class WikiEvent extends Event<WikiPage>{
	private final UmbrellaUser newMember;

	public WikiEvent(UmbrellaUser initiator, WikiPage page, EventType type){
		super(initiator, WIKI, page, type);
		newMember = null;
	}

	public WikiEvent(UmbrellaUser initiator, WikiPage page, Map<String, Object> oldData){
		super(initiator, WIKI, page, oldData);
		newMember = null;
	}

	public WikiEvent(UmbrellaUser initiator, WikiPage page, UmbrellaUser newMember){
		super(initiator,WIKI,page,MEMBER_ADDED);
		this.newMember = newMember;
	}

	@Override
	public Collection<UmbrellaUser> audience() {
		return payload().members().values().stream().map(Member::user).toList();
	}

	@Override
	public Translatable describe() {
		return switch (eventType()){
			case CREATE -> describeCreate();
			case DELETE -> describeDelete();
			case MEMBER_ADDED ->  describeMemberAdded();
			case UPDATE -> describeUpdate();
		};
	}

	public Translatable describeCreate(){
		var head = t("New wiki page {name} has been created");
		return t("{head}:\n\n{object}\n\n{link}","head",head,OBJECT,payload().content(),"link",link());
	}

	public Translatable describeDelete(){
		return t("The wiki page '{page}' has been deleted by {user}", "page", payload().title(), USER, initiator().name());
	}

	public Translatable describeMemberAdded(){
		var head = t("'{name}' has been added to '{object}' by '{user}'.",NAME,newMember.name(), OBJECT,payload().title(),USER,initiator().name());
		return t("{head}\n\n{link}","head",head,"link",link());
	}

	private Translatable describeUpdate() {
		var head = t("Changes in wiki page '{id}':\n\n{body}",Field.ID,payload().title(),BODY,diff().orElse(""));
		return t("{head}\n\n{link}","head",head,"link",link());
	}

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


	@Override
	public Translatable subject() {
		return switch (eventType()){
			case CREATE -> t("The wiki page '{name}' has been created", Field.NAME, payload().title());
			case DELETE -> t("The wiki page '{name}' has been deleted",Field.NAME, payload().title());
			case MEMBER_ADDED, UPDATE -> t("wiki page '{name}' was edited",Field.NAME,payload().title());
		};
	}
}
