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


import static de.srsoftware.tools.Optionals.nullable;
import static de.srsoftware.umbrella.core.ModuleRegistry.projectService;
import static de.srsoftware.umbrella.core.ModuleRegistry.userService;
import static de.srsoftware.umbrella.core.Util.mapValues;
import static de.srsoftware.umbrella.core.constants.Field.TOKEN;
import static de.srsoftware.umbrella.core.constants.Field.USERS;
import static de.srsoftware.umbrella.core.constants.Path.JSON;

import com.sun.net.httpserver.HttpExchange;
import de.srsoftware.configuration.Configuration;
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.Map;
import java.util.Optional;

public class ProjectLegacy extends BaseHandler {

	public ProjectLegacy(Configuration config) {
		super();
	}

	@Override
	public boolean doDelete(Path path, HttpExchange ex) throws IOException {
		return super.doDelete(path, ex);
	}

	@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 -> postProjectJson(ex,params,user.get());
			default -> super.doPost(path, ex);
		};
	}

	private boolean postProjectJson(HttpExchange ex, Map<String, Object> params, UmbrellaUser user) throws IOException {
		var includeUsers = "1".equals(params.get(USERS));
		var projects = projectService().listUserProjects(user.id(), false);
		return sendContent(ex, mapValues(projects));
	}
}
