import {
  pgTable,
  text,
  timestamp,
  uuid,
  boolean,
  integer,
  index,
} from "drizzle-orm/pg-core";

// ---------------------------------------------------------------------------
// Affiliate schema — aligned to PRODUCTION as of 2026-05-19 baseline.
// Tables: member_profiles, recommended_products, product_clicks
// (legacy migration 0015_affiliate).
//
// Backs the public affiliate product page at tia.<domain>/m/[slug].
// ---------------------------------------------------------------------------

export const memberProfiles = pgTable(
  "member_profiles",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    userId: uuid("user_id").notNull().unique(),
    familyId: uuid("family_id").notNull(),
    slug: text("slug").notNull(),
    displayName: text("display_name").notNull(),
    bio: text("bio"),
    avatarUrl: text("avatar_url"),
    isPublic: boolean("is_public").default(false).notNull(),
    createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(),
    updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(),
  },
  (table) => [index("member_profiles_slug_idx").on(table.slug)]
);

export const recommendedProducts = pgTable(
  "recommended_products",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    profileId: uuid("profile_id").notNull(),
    title: text("title").notNull(),
    description: text("description"),
    url: text("url").notNull(),
    imageUrl: text("image_url"),
    category: text("category").default("general").notNull(),
    displayOrder: integer("display_order").default(0).notNull(),
    isActive: boolean("is_active").default(true).notNull(),
    createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(),
  },
  (table) => [
    index("recommended_products_profile_idx").on(table.profileId, table.displayOrder),
  ]
);

// Click tracking — ipHash is a hash, never a raw IP (privacy).
export const productClicks = pgTable(
  "product_clicks",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    productId: uuid("product_id").notNull(),
    clickedAt: timestamp("clicked_at", { withTimezone: true }).defaultNow().notNull(),
    referrer: text("referrer"),
    ipHash: text("ip_hash"),
  },
  (table) => [index("product_clicks_product_idx").on(table.productId, table.clickedAt)]
);

export type MemberProfile = typeof memberProfiles.$inferSelect;
export type RecommendedProduct = typeof recommendedProducts.$inferSelect;
export type ProductClick = typeof productClicks.$inferSelect;
