/* © SRSoftware 2025 */
package de.srsoftware.umbrella.legacy;



import static de.srsoftware.tools.Optionals.nullable;
import static de.srsoftware.umbrella.core.ModuleRegistry.taskService;
import static de.srsoftware.umbrella.core.ModuleRegistry.userService;
import static de.srsoftware.umbrella.core.Util.mapValues;
import static de.srsoftware.umbrella.core.constants.Field.*;
import static de.srsoftware.umbrella.core.constants.Path.JSON;
import static de.srsoftware.umbrella.core.exceptions.UmbrellaException.unprocessable;

import com.sun.net.httpserver.HttpExchange;
import de.srsoftware.tools.Path;
import de.srsoftware.tools.SessionToken;
import de.srsoftware.umbrella.core.BaseHandler;
import de.srsoftware.umbrella.core.model.Token;
import de.srsoftware.umbrella.core.model.UmbrellaUser;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Optional;

public class TaskLegacy extends BaseHandler {

	public TaskLegacy() {
		super();
	}

	@Override
	public boolean doGet(Path path, HttpExchange ex) throws IOException {
		var url = url(ex);
		if (path.empty() || url.endsWith("/view")) return sendRedirect(ex, url.replaceAll("/legacy/","/"));
		return super.doGet(path, ex);
	}

	@Override
	public boolean doPost(Path path, HttpExchange ex) throws IOException {
		var params = formData(ex);

		Optional<Token> token = SessionToken.from(ex).map(Token::of);
		if (token.isEmpty()) token = nullable(params.get(TOKEN)).map(Object::toString).map(Token::of);
		var user = userService().loadUser(token);
		if (user.isEmpty()) return unauthorized(ex);

		return switch (path.pop()){
			case JSON -> postJson(user.get(),params,ex);
			case null, default -> super.doPost(path,ex);
		};
	}

	private boolean postJson(UmbrellaUser umbrellaUser, Map<String, Object> params, HttpExchange ex) throws IOException {
		if (params.get("ids") instanceof String sid){
			var taskId = Long.parseLong(sid);
			var task = taskService().load(List.of(taskId)).values().stream().toList().getFirst();
			var map = task.toMap();
			map.put(DESCRIPTION,task.description());
			return sendContent(ex,map);
		}
		if (params.get("ids") instanceof Map<?,?> taskIdMap){
			var taskIds = taskIdMap.values().stream().map(Object::toString).map(Long::parseLong).toList();
			return sendContent(ex,mapValues(taskService().load(taskIds)));
		}
		throw unprocessable("Invalid request");
	}
}
