import {
	boolean,
	integer,
	jsonb,
	pgEnum,
	pgTable,
	text,
	timestamp,
	uniqueIndex,
	uuid,
} from "drizzle-orm/pg-core";
import { createInsertSchema, createSelectSchema } from "drizzle-zod";

import { z } from "zod";

export const settingType = pgEnum("setting_type", [
	"feature", // when changed deals with triggering the croner related to this
	"system", // when changed fires a system restart but this should be rare and all these settings should be in the env
	"standard", // will be effected by the next process, either croner or manual trigger
]);

export const settings = pgTable(
	"settings",
	{
		id: uuid("settings_id").defaultRandom().primaryKey(),
		name: text("name").notNull(),
		value: text("value").notNull(), // this is used in junction with active, only needed if the setting isn't a bool
		description: text("description"),
		moduleName: text("moduleName"), // what part of lst dose it belong to this is used to split the settings out later
		active: boolean("active").default(true),
		roles: jsonb("roles").$type<string[]>().notNull().default(["systemAdmin"]), // role or roles to see this goes along with the moduleName, need to have a x role in module to see this setting.
		settingType: settingType(),
		seedVersion: integer("seed_version").default(1), // this is intended for if we want to update the settings.
		add_User: text("add_User").default("LST_System").notNull(),
		add_Date: timestamp("add_Date", { withTimezone: true }).defaultNow(),
		upd_user: text("upd_User").default("LST_System").notNull(),
		upd_date: timestamp("upd_date", { withTimezone: true }).defaultNow(),
	},
	(table) => [
		// uniqueIndex('emailUniqueIndex').on(sql`lower(${table.email})`),
		uniqueIndex("settings_name_unique").on(table.name),
	],
);

export const settingSchema = createSelectSchema(settings);
export const newSettingSchema = createInsertSchema(settings, {
	name: z.string().min(3, {
		message: "The name of the setting must be longer than 3 letters",
	}),
});

export type Setting = z.infer<typeof settingSchema>;
export type NewSetting = z.infer<typeof newSettingSchema>;
