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

export const appsTable = pgTable("apps", {
  id: serial("id").primaryKey(),
  slug: varchar("slug", { length: 100 }).notNull().unique(),
  nameAr: varchar("name_ar", { length: 200 }).notNull(),
  nameEn: varchar("name_en", { length: 200 }).notNull(),
  descriptionAr: text("description_ar"),
  descriptionEn: text("description_en"),
  iconName: varchar("icon_name", { length: 100 }).notNull().default("Grid"),
  // Optional uploaded image used in place of the Lucide icon on the
  // launcher tile. Stored as the object-storage path (e.g. "/objects/<id>")
  // returned by the upload presigner, so resolveServiceImageUrl knows how
  // to translate it for the browser.
  imageUrl: varchar("image_url", { length: 500 }),
  route: varchar("route", { length: 500 }).notNull(),
  // For openMode "external_tab"|"external_iframe": the target URL.
  // Ignored when openMode is "internal".
  externalUrl: varchar("external_url", { length: 1000 }),
  // How the launcher should open this app:
  //   internal       — navigate to `route` inside the SPA (default)
  //   external_tab   — window.open(externalUrl, "_blank")
  //   external_iframe— navigate to /embedded/:id, which renders externalUrl in an iframe shell
  openMode: varchar("open_mode", { length: 20 }).notNull().default("internal"),
  color: varchar("color", { length: 50 }).notNull().default("#6366f1"),
  isActive: boolean("is_active").notNull().default(true),
  isSystem: boolean("is_system").notNull().default(false),
  sortOrder: integer("sort_order").notNull().default(0),
  createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
  updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow().$onUpdate(() => new Date()),
});

export const appPermissionsTable = pgTable("app_permissions", {
  appId: integer("app_id").notNull().references(() => appsTable.id, { onDelete: "cascade" }),
  permissionId: integer("permission_id").notNull(),
}, (t) => [primaryKey({ columns: [t.appId, t.permissionId] })]);

export const insertAppSchema = createInsertSchema(appsTable).omit({ id: true, createdAt: true, updatedAt: true });
export type InsertApp = z.infer<typeof insertAppSchema>;
export type App = typeof appsTable.$inferSelect;
