/* © SRSoftware 2025 */
package de.srsoftware.umbrella.core.model;

import static de.srsoftware.umbrella.core.constants.Field.NAME;
import static de.srsoftware.umbrella.core.constants.Field.STATUS;
import static de.srsoftware.umbrella.core.exceptions.UmbrellaException.*;

import de.srsoftware.tools.Mappable;
import de.srsoftware.umbrella.core.constants.Field;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public record Status(String name, int code) implements Mappable {
	public static final Status PENDING = new Status("PENDING", 10); // was 40
	public static final Status OPEN = new Status("OPEN",20); // was 10
	public static final Status STARTED = new Status("STARTED",40); // was 20
	public static final Status COMPLETE = new Status("COMPLETE",60);
	public static final Status CANCELLED = new Status("CANCELLED", 100);
	public static final List<Status> PREDEFINED = List.of(OPEN, STARTED, PENDING, COMPLETE, CANCELLED);

	public static Status matching(String name){
		return switch (name.toLowerCase()){
			case "pending" -> PENDING;
			case "open" -> OPEN;
			case "started" -> STARTED;
			case "complete" -> COMPLETE;
			case "cancelled" -> CANCELLED;
			case null, default -> throw invalidField(STATUS,"one of: "+PREDEFINED.stream().map(Status::name).collect(Collectors.joining(", ")));
		};
	}

	public static Status of(int code){
		return switch (code){
			case 10 -> PENDING;
			case 20 -> OPEN;
			case 40 -> STARTED;
			case 60 -> COMPLETE;
			case 100 -> CANCELLED;
			default -> throw new IllegalArgumentException();
		};
	}

	public static Status of(ResultSet rs) throws SQLException {
		return new Status(rs.getString(NAME),rs.getInt(Field.CODE));
	}

	@Override
	public Map<String, Object> toMap() {
		return Map.of(NAME,name, Field.CODE,code);
	}
}