import { pgTable, text, timestamp, boolean, primaryKey } from "drizzle-orm/pg-core";
import { relations } from "drizzle-orm";
import { users, tierEnum } from "./users";

/** Absence of a row for a (featureKey, tier) pair means "enabled" — rows only
 *  exist to record an override, so adding a new gated feature never requires
 *  a backfill. */
export const featureFlags = pgTable("feature_flags", {
  featureKey: text("feature_key").notNull(),
  tier: tierEnum("tier").notNull(),
  enabled: boolean("enabled").notNull().default(true),
  updatedAt: timestamp("updated_at").notNull().defaultNow(),
  updatedById: text("updated_by_id").references(() => users.id, { onDelete: "set null" }),
}, (t) => [
  primaryKey({ columns: [t.featureKey, t.tier] }),
]);

export const featureFlagsRelations = relations(featureFlags, ({ one }) => ({
  updatedBy: one(users, { fields: [featureFlags.updatedById], references: [users.id] }),
}));

// One row per "I'm interested" click from a locked-feature upgrade dialog —
// lets admins see which locked features are actually driving upgrade
// interest (Admin -> Insights), not just that upgrades happen.
export const featureUpgradeClicks = pgTable("feature_upgrade_clicks", {
  id: text("id").primaryKey(),
  userId: text("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
  featureKey: text("feature_key").notNull(),
  createdAt: timestamp("created_at").notNull().defaultNow(),
});

export const featureUpgradeClicksRelations = relations(featureUpgradeClicks, ({ one }) => ({
  user: one(users, { fields: [featureUpgradeClicks.userId], references: [users.id] }),
}));
