import {
  pgTable,
  text,
  timestamp,
  uuid,
  varchar,
  check,
} from "drizzle-orm/pg-core";
import { sql } from "drizzle-orm";

// ---------------------------------------------------------------------------
// Admin / auth-extra schema — aligned to PRODUCTION as of 2026-05-19 baseline.
// Tables: admins, admin_sessions, password_resets
// (legacy migrations 0006_admin_auth, 0009_admin_sessions, 0004's password_resets).
//
// SECURITY NOTE: `admins` is the privileged back-office account table, fully
// separate from the `users` table. Password hashes here gate admin access —
// treat any change to this table as security-critical.
// ---------------------------------------------------------------------------

export const admins = pgTable(
  "admins",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    username: varchar("username", { length: 50 }).notNull().unique(),
    passwordHash: varchar("password_hash", { length: 255 }).notNull(),
    role: varchar("role", { length: 20 }).default("admin"),
    createdAt: timestamp("created_at", { withTimezone: true }).defaultNow(),
    lastLogin: timestamp("last_login", { withTimezone: true }),
  },
  (table) => [
    check(
      "admins_role_check",
      sql`(role)::text = ANY (ARRAY['super_admin','admin','support'])`
    ),
  ]
);

export const adminSessions = pgTable("admin_sessions", {
  id: uuid("id").primaryKey().defaultRandom(),
  adminId: uuid("admin_id").notNull(),
  sessionToken: text("session_token").notNull().unique(),
  expires: timestamp("expires", { withTimezone: true }).notNull(),
  createdAt: timestamp("created_at", { withTimezone: true }).defaultNow(),
});

export const passwordResets = pgTable("password_resets", {
  id: uuid("id").primaryKey().defaultRandom(),
  userId: uuid("user_id").notNull(),
  token: text("token").notNull().unique(),
  expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
  usedAt: timestamp("used_at", { withTimezone: true }),
});

export type Admin = typeof admins.$inferSelect;
export type AdminSession = typeof adminSessions.$inferSelect;
export type PasswordReset = typeof passwordResets.$inferSelect;
