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

export const users = pgTable("users", {
  id: uuid("id").primaryKey().defaultRandom(),
  email: varchar("email", { length: 255 }).notNull().unique(),
  password: varchar("password", { length: 255 }).notNull(), // scrypt hash
  fullName: varchar("full_name", { length: 255 }).notNull(), // ФИО
  role: roleNameEnum("role").notNull().default("manager"),
  currentBranchId: uuid("current_branch_id").references(() => branches.id), // Текущий выбранный филиал
  createdAt: timestamp("created_at", { withTimezone: true })
    .defaultNow()
    .notNull(),
  updatedAt: timestamp("updated_at", { withTimezone: true })
    .defaultNow()
    .notNull(),
});

// Zod schemas for validation
export const insertUserSchema = createInsertSchema(users);
export const selectUserSchema = createSelectSchema(users);

// Relations
export const usersRelations = relations(users, ({ one, many }) => ({
  serverSessions: many(serverSessions),
  authSessions: many(authSessions),
  userBranches: many(userBranches),
  currentBranch: one(branches, {
    fields: [users.currentBranchId],
    references: [branches.id],
  }),
}));

// Type exports
export type User = typeof users.$inferSelect;
export type NewUser = typeof users.$inferInsert;
