import {
    pgTable,
    bigint,
    text,
    timestamp,
    boolean,
    jsonb,
    integer,
    index,
    uuid,
    AnyPgColumn
} from "drizzle-orm/pg-core"
import { relations } from "drizzle-orm"
import { tenants } from "./tenants"
import { authUsers } from "./auth_users"

export const wikiPages = pgTable(
    "wiki_pages",
    {
        // ID des Wiki-Eintrags selbst (neu = UUID)
        id: uuid("id")
            .primaryKey()
            .defaultRandom(),

        tenantId: bigint("tenant_id", { mode: "number" })
            .notNull()
            .references(() => tenants.id, { onDelete: "cascade" }),

        parentId: uuid("parent_id")
            .references((): AnyPgColumn => wikiPages.id, { onDelete: "cascade" }),

        title: text("title").notNull(),

        content: jsonb("content"),

        isFolder: boolean("is_folder").notNull().default(false),

        sortOrder: integer("sort_order").notNull().default(0),

        // --- POLYMORPHE BEZIEHUNG (Split) ---

        // Art der Entität (z.B. 'customer', 'invoice', 'iot_device')
        entityType: text("entity_type"),

        // SPALTE 1: Für Legacy-Tabellen (BigInt)
        // Nutzung: Wenn entityType='customer', wird hier die ID 1050 gespeichert
        entityId: bigint("entity_id", { mode: "number" }),

        // SPALTE 2: Für neue Tabellen (UUID)
        // Nutzung: Wenn entityType='iot_device', wird hier die UUID gespeichert
        entityUuid: uuid("entity_uuid"),

        // ------------------------------------

        createdAt: timestamp("created_at", { withTimezone: true })
            .notNull()
            .defaultNow(),

        updatedAt: timestamp("updated_at", { withTimezone: true }),

        createdBy: uuid("created_by").references(() => authUsers.id),
        updatedBy: uuid("updated_by").references(() => authUsers.id),
    },
    (table) => ({
        tenantIdx: index("wiki_pages_tenant_idx").on(table.tenantId),
        parentIdx: index("wiki_pages_parent_idx").on(table.parentId),

        // ZWEI separate Indexe für schnelle Lookups, je nachdem welche ID genutzt wird
        // Fall 1: Suche nach Notizen für Kunde 1050
        entityIntIdx: index("wiki_pages_entity_int_idx")
            .on(table.tenantId, table.entityType, table.entityId),

        // Fall 2: Suche nach Notizen für IoT-Device 550e84...
        entityUuidIdx: index("wiki_pages_entity_uuid_idx")
            .on(table.tenantId, table.entityType, table.entityUuid),
    })
)

export const wikiPagesRelations = relations(wikiPages, ({ one, many }) => ({
    tenant: one(tenants, {
        fields: [wikiPages.tenantId],
        references: [tenants.id],
    }),
    parent: one(wikiPages, {
        fields: [wikiPages.parentId],
        references: [wikiPages.id],
        relationName: "parent_child",
    }),
    children: many(wikiPages, {
        relationName: "parent_child",
    }),
    author: one(authUsers, {
        fields: [wikiPages.createdBy],
        references: [authUsers.id],
    }),
}))

export type WikiPage = typeof wikiPages.$inferSelect
export type NewWikiPage = typeof wikiPages.$inferInsert