import { relations } from "drizzle-orm";
import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core";

// MYP tables
export const printers = sqliteTable("printer", {
	id: text("id")
		.primaryKey()
		.$defaultFn(() => crypto.randomUUID()),
	name: text("name").notNull(),
	description: text("description").notNull(),
	status: integer("status").notNull().default(0),
});
export const printerRelations = relations(printers, ({ many }) => ({
	printJobs: many(printJobs),
}));

export const printJobs = sqliteTable("printJob", {
	id: text("id")
		.primaryKey()
		.$defaultFn(() => crypto.randomUUID()),
	printerId: text("printerId")
		.notNull()
		.references(() => printers.id, {
			onDelete: "cascade",
		}),
	userId: text("userId")
		.notNull()
		.references(() => users.id, {
			onDelete: "cascade",
		}),
	startAt: integer("startAt", { mode: "timestamp_ms" })
		.notNull()
		.$defaultFn(() => new Date()),
	durationInMinutes: integer("durationInMinutes").notNull(),
	comments: text("comments"),
	aborted: integer("aborted", { mode: "boolean" }).notNull().default(false),
	abortReason: text("abortReason"),
});
export const printJobRelations = relations(printJobs, ({ one }) => ({
	printer: one(printers, {
		fields: [printJobs.printerId],
		references: [printers.id],
	}),
	user: one(users, {
		fields: [printJobs.userId],
		references: [users.id],
	}),
}));

// Auth Tables
export const users = sqliteTable("user", {
	id: text("id").notNull().primaryKey(),
	github_id: integer("github_id").notNull(),
	username: text("name"),
	displayName: text("displayName"),
	email: text("email").notNull(),
	role: text("role").default("guest"),
});
export const userRelations = relations(users, ({ many }) => ({
	printJobs: many(printJobs),
	sessions: many(sessions),
}));

export const sessions = sqliteTable("session", {
	id: text("id").notNull().primaryKey(),
	userId: text("user_id")
		.notNull()
		.references(() => users.id, {
			onDelete: "cascade",
		}),
	expiresAt: integer("expires_at").notNull(),
});
export const sessionRelations = relations(sessions, ({ one }) => ({
	user: one(users, {
		fields: [sessions.userId],
		references: [users.id],
	}),
}));
