import { getRecentLogs } from "../db/db.socketSeed.js";
import { getRecentDockScans } from "../dockdoorScanning/dockdoor.socket.seed.js";

export type RoomKey =
	| "logs"
	| "labels"
	| "admin"
	| "inventory"
	| "dockDoorLoading"
	| "scanLog";

export type SocketUser = {
	id: string;
	email?: string;
	role?: string;
};

export type CanJoinArgs = {
	socket: any;
	user?: SocketUser;
	room: string;
	actualRoom: string;
	params?: Record<string, unknown>;
};

type RoomConfig = {
	//requiresAuth?: boolean;
	//roles?: string[];
	canJoin?: (args: CanJoinArgs) => boolean | Promise<boolean>;
	buildRoom?: (params?: Record<string, unknown>) => string | null;
	seed?: (args: {
		room: string;
		actualRoom: string;
		params?: Record<string, unknown>;
		user?: SocketUser;
	}) => Promise<unknown[]>;
};

export function isRoomKey(room: string): room is RoomKey {
	return room in roomConfigs;
}

export const roomConfigs: Record<RoomKey, RoomConfig> = {
	logs: {
		canJoin: ({ user, params }) => {
			if (!params?.submodule && !params?.module) {
				return user?.role === "systemAdmin";
			}

			return true;
		},
		buildRoom: (params) => {
			const module = String(params?.module ?? "").toLowerCase();
			const submodule = String(params?.submodule ?? "").toLowerCase();

			if (module && submodule) return `logs:${module}:${submodule}`;
			if (submodule) return `logs:${submodule}`;
			if (module) return `logs:${module}`;

			return "logs";
		},
		seed: async ({ params }) => {
			const module = params?.module ? String(params.module) : undefined;
			const submodule = params?.submodule
				? String(params.submodule)
				: undefined;

			return await getRecentLogs({
				module,
				submodule,
				limit: 200,
			});
		},
	},

	labels: {
		canJoin: () => true,
		buildRoom: () => "labels",
	},

	admin: {
		canJoin: ({ user, params }) => {
			if (params?.section === "system") {
				return user?.role === "systemAdmin";
			}

			return true;
		},
		buildRoom: (params) =>
			params?.section ? `admin:${params.section}` : "admin",
	},
	inventory: {
		canJoin: () => true,
		buildRoom: (params) =>
			params?.location ? `inventory:${params.location}` : null,
	},

	dockDoorLoading: {
		canJoin: () => true,
		buildRoom: (params) =>
			params?.dockId ? `dockDoorLoading:${params.dockId}` : null,
		seed: async ({ params }) => {
			return await getRecentDockScans({
				loadingOrder: params?.loadingOrder as string,
				limit: 200,
			});
		},
	},

	scanLog: {
		canJoin: () => true,
		buildRoom: () => "scanLog",
	},
} satisfies Record<string, RoomConfig>;

/*

socket.emit("join-room", {
  room: "dockDoorLoading",
  params: { dockId: "2" },
});

*/
