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


import static de.srsoftware.tools.Optionals.nullable;
import static de.srsoftware.umbrella.core.ModuleRegistry.companyService;
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.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 CompanyLegacy extends BaseHandler {

	public CompanyLegacy(Configuration config) {
		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 -> postCompanyJson(ex,params,user.get());
			default -> super.doPost(path, ex);
		};
	}

	private boolean postCompanyJson(HttpExchange ex, Map<String, Object> params, UmbrellaUser user) throws IOException {
		var companies = companyService().listCompaniesOf(user);
		return sendContent(ex, mapValues(companies));
	}


}
