import {
  pgTable,
  uuid,
  varchar,
  pgEnum,
  timestamp,
  integer,
} from "drizzle-orm/pg-core";
import { relations } from "drizzle-orm";
import { createInsertSchema, createSelectSchema } from "drizzle-zod";
import { serverSessions } from "./serverSessions";
import { branches } from "./branches";

// Enums
export const serverLocationEnum = pgEnum("server_location", ["ru1", "uae1"]);
export const serverTypeEnum = pgEnum("server_type", ["stream", "local"]);
export const serverTierEnum = pgEnum("server_tier", ["demo", "prod"]);

export const servers = pgTable("servers", {
  id: uuid("id").primaryKey().defaultRandom(),
  localIp: varchar("local_ip", { length: 45 }).notNull(), // IPv6 can be up to 45 chars
  hostname: varchar("hostname").notNull(), // hostname сервера
  type: serverTypeEnum("type").notNull(), // stream, local
  gpuFreeMb: integer("gpu_free_mb").notNull(), // свободная память на GPU в мегабайтах
  branchId: uuid("branch_id").references(() => branches.id), // филиал, на котором находится сервер (nullable для локальных серверов)
  location: serverLocationEnum("location"), // ru1, uae1 (только для stream)
  tier: serverTierEnum("tier"), // demo, prod (только для stream)
  createdAt: timestamp("created_at", { withTimezone: true })
    .defaultNow()
    .notNull(),
  updatedAt: timestamp("updated_at", { withTimezone: true })
    .defaultNow()
    .notNull(),
});

// Zod schemas for validation
export const insertServerSchema = createInsertSchema(servers).refine(
  (data) => {
    // Если тип "stream", то location и tier обязательны
    if (data.type === "stream") {
      return data.location !== undefined && data.location !== null;
    }
    return true;
  },
  {
    message: "Location is required for stream servers",
    path: ["location"],
  }
);

export const selectServerSchema = createSelectSchema(servers);

// Relations
export const serversRelations = relations(servers, ({ many }) => ({
  serverSessions: many(serverSessions),
}));

// Type exports
export type Server = typeof servers.$inferSelect;
export type NewServer = typeof servers.$inferInsert;
