import { pgTable, varchar, integer, timestamp, boolean } from "drizzle-orm/pg-core";
import { createInsertSchema } from "drizzle-zod";
import { z } from "zod/v4";

export const appSettingsTable = pgTable("app_settings", {
  id: integer("id").primaryKey().default(1),
  siteNameAr: varchar("site_name_ar", { length: 200 }).notNull().default("نظام Tx"),
  siteNameEn: varchar("site_name_en", { length: 200 }).notNull().default("Tx OS"),
  registrationOpen: boolean("registration_open").notNull().default(true),
  footerTextAr: varchar("footer_text_ar", { length: 300 }).notNull().default("جميع الحقوق محفوظة."),
  footerTextEn: varchar("footer_text_en", { length: 300 }).notNull().default("All rights reserved."),
  updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow().$onUpdate(() => new Date()),
});

export const updateAppSettingsSchema = createInsertSchema(appSettingsTable)
  .omit({ id: true, updatedAt: true })
  .partial();
export type AppSettings = typeof appSettingsTable.$inferSelect;
export type UpdateAppSettings = z.infer<typeof updateAppSettingsSchema>;

// ---------------------------------------------------------------------------
// system_settings — single-row install-state record consumed by the
// First-Time Setup Wizard. Distinct from `app_settings` (which holds
// admin-editable site config). The row id is always 1; the wizard upserts
// it once during /api/setup/complete and never deletes it.
// ---------------------------------------------------------------------------
export const systemSettingsTable = pgTable("system_settings", {
  id: integer("id").primaryKey().default(1),
  installed: boolean("installed").notNull().default(false),
  installedAt: timestamp("installed_at", { withTimezone: true }),
  baseUrl: varchar("base_url", { length: 500 }),
  localDomain: varchar("local_domain", { length: 200 }),
  localIp: varchar("local_ip", { length: 64 }),
  httpsMode: varchar("https_mode", { length: 16 }).notNull().default("local"),
  appVersion: varchar("app_version", { length: 64 }),
  updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow().$onUpdate(() => new Date()),
});

export type SystemSettings = typeof systemSettingsTable.$inferSelect;
