import { desc } from "drizzle-orm";
import { db } from "../db/db.controller.js";
import { logs } from "../db/schema/logs.schema.js";
import { ppoRun } from "../warehousing/warehousing.ppooMonitor.js";

type RoomDefinition<T = unknown> = {
	seed: (limit: number) => Promise<T[]>;
};

export type StaticRoomId = "logs" | "labels" | "admin" | "admin:build" | "ppoo";
export type DynamicRoomId = `dockDoorLoading:${string}`;
export type RoomId = StaticRoomId | DynamicRoomId;

export type RoomConfig = {
	requiresAuth?: boolean;
	role?: string[];
	seed?: (limit: number, roomId: RoomId) => Promise<unknown[]>;
};

export const protectedRooms: Record<StaticRoomId, RoomConfig> = {
	logs: { requiresAuth: true, role: ["admin", "systemAdmin"] },
	//admin: { requiresAuth: false, role: ["admin", "systemAdmin"] },
	labels: {},
	admin: {},
	"admin:build": {},
	ppoo: {},
};

export function getRoomConfig(roomId: string): RoomConfig | null {
	if (roomId in protectedRooms) {
		return protectedRooms[roomId as StaticRoomId];
	}

	if (roomId.startsWith("dockDoorLoading:")) {
		const dockId = roomId.split(":")[1];

		if (!dockId) return null;

		return {
			requiresAuth: true,
			role: ["admin", "systemAdmin", "dockDoor"],
		};
	}

	return null;
}

export const roomDefinition: Record<RoomId, RoomDefinition> = {
	logs: {
		seed: async (limit) => {
			try {
				const rows = await db
					.select()
					.from(logs)
					.orderBy(desc(logs.createdAt))
					.limit(limit);

				return rows; //.reverse();
			} catch (e) {
				console.error("Failed to seed logs:", e);
				return [];
			}
		},
	},

	labels: {
		seed: async (limit) => {
			console.info(limit);
			return [];
		},
	},
	admin: {
		seed: async (limit) => {
			console.info(limit);
			return [];
		},
	},
	"admin:build": {
		seed: async (limit) => {
			console.info(limit);
			return [];
		},
	},
	ppoo: {
		seed: async (limit) => {
			console.log(limit);
			return {
				type: "snapshot",
				items: await ppoRun(),
				createdAt: new Date().toISOString(),
			} as any;
		},
	},
};
