import { pgTable, uuid, integer, timestamp, pgEnum } from "drizzle-orm/pg-core";
import { servers } from "./servers";
import { apps } from "./apps";
import { users } from "./users";
import { relations } from "drizzle-orm";
import { createInsertSchema, createSelectSchema } from "drizzle-zod";

// Enums
export const sessionModeEnum = pgEnum("session_mode", ["stream", "local"]);
export const sessionStatusEnum = pgEnum("session_status", [
  "starting",
  "started",
  "ending",
  "ended",
]);

export const serverSessions = pgTable("server_sessions", {
  id: uuid("id").primaryKey().defaultRandom(),
  serverId: uuid("server_id").references(() => servers.id), // Nullable - для stream сессий назначается динамически
  appId: uuid("app_id")
    .notNull()
    .references(() => apps.id),
  userId: uuid("user_id")
    .notNull()
    .references(() => users.id),
  startAt: timestamp("start_at", { withTimezone: true })
    .defaultNow()
    .notNull(),
  endAt: timestamp("end_at", { withTimezone: true }), // Default 30 minutes from start_at
  appPid: integer("app_pid"),
  cirrusPid: integer("cirrus_pid"),
  mode: sessionModeEnum("mode").notNull(), // stream, local
  status: sessionStatusEnum("status").notNull(), // starting, started, ending, ended
  createdAt: timestamp("created_at", { withTimezone: true })
    .defaultNow()
    .notNull(),
  updatedAt: timestamp("updated_at", { withTimezone: true })
    .defaultNow()
    .notNull(),
});

// Relations
export const serverSessionsRelations = relations(serverSessions, ({ one }) => ({
  app: one(apps, {
    fields: [serverSessions.appId],
    references: [apps.id],
  }),
  user: one(users, {
    fields: [serverSessions.userId],
    references: [users.id],
  }),
  server: one(servers, {
    fields: [serverSessions.serverId],
    references: [servers.id],
  }),
}));

// Zod schemas for validation
export const insertServerSessionSchema = createInsertSchema(serverSessions);
export const selectServerSessionSchema = createSelectSchema(serverSessions);

// Type exports
export type ServerSession = typeof serverSessions.$inferSelect;
export type NewServerSession = typeof serverSessions.$inferInsert;
