import {
    pgTable,
    serial,
    varchar,
    boolean,
    text,
    timestamp,
    bigint,
    integer,
    index,
} from 'drizzle-orm/pg-core';
import { relations, type InferSelectModel } from 'drizzle-orm';

export type FeatureFlag = InferSelectModel<typeof featureFlags>;
export type FeatureFlagAccess = InferSelectModel<typeof featureFlagAccess>;

export const featureFlags = pgTable('feature_flags', {
    id: serial('id').primaryKey(),
    name: varchar('name', { length: 100 }).notNull().unique(),
    enabled: boolean('enabled').default(false).notNull(),
    description: text('description'),
    createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
    updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
});

export const featureFlagAccess = pgTable('feature_flag_access', {
    id: serial('id').primaryKey(),
    flagId: integer('flag_id').notNull().references(() => featureFlags.id, { onDelete: 'cascade' }),
    guildId: bigint('guild_id', { mode: 'bigint' }),
    userId: bigint('user_id', { mode: 'bigint' }),
    roleId: bigint('role_id', { mode: 'bigint' }),
    createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
}, (table) => [
    index('idx_ffa_flag_id').on(table.flagId),
    index('idx_ffa_guild_id').on(table.guildId),
    index('idx_ffa_user_id').on(table.userId),
    index('idx_ffa_role_id').on(table.roleId),
]);

export const featureFlagsRelations = relations(featureFlags, ({ many }) => ({
    access: many(featureFlagAccess),
}));

export const featureFlagAccessRelations = relations(featureFlagAccess, ({ one }) => ({
    flag: one(featureFlags, {
        fields: [featureFlagAccess.flagId],
        references: [featureFlags.id],
    }),
}));
