import {
  pgTable,
  text,
  timestamp,
  uuid,
  pgEnum,
  varchar,
  integer,
  date,
  uniqueIndex,
  index,
} from "drizzle-orm/pg-core";

// ---------------------------------------------------------------------------
// Family schema — aligned to PRODUCTION as of 2026-05-19 baseline.
// Source of truth: drizzle-kit pull against tia_prod.
//
// Drift corrected at baseline:
//  - families:        added tier / maxChildren / maxMembers (legacy 0005)
//  - children:        col is `stage` not `current_stage`; `image_url` not
//                     `profile_photo_url`; dropped phantom `stage_overrides`;
//                     birth_date is DATE; sex is NULLABLE
//  - family_members:  dropped phantom `display_name`
//  - family_invites:  dropped phantom `display_name` / `accepted_at`
// ---------------------------------------------------------------------------

// Enums
export const memberRoleEnum = pgEnum("member_role", ["admin", "caregiver", "viewer"]);
export const childSexEnum = pgEnum("child_sex", ["male", "female", "other"]);
export const childStageEnum = pgEnum("child_stage", [
  "newborn",
  "infant",
  "solids_start",
  "toddler_early",
  "toddler_late",
  "preschool",
]);

// Families table
export const families = pgTable("families", {
  id: uuid("id").primaryKey().defaultRandom(),
  name: text("name").notNull(),
  // Tier / subscription — payment abstraction (migration 0005 + 0007).
  // tier:               'free' | 'pro' (or any non-'free' value = paid)
  // subscriptionStatus: set by payment-provider webhook: 'active' | 'canceled' | 'past_due' | null
  // All quota/member enforcement reads through isPaidFamily() in src/lib/quota.ts.
  tier: varchar("tier", { length: 20 }).default("free"),
  subscriptionStatus: varchar("subscription_status", { length: 20 }),
  maxChildren: integer("max_children").default(1),
  maxMembers: integer("max_members").default(2),
  pediatricianPhone: text("pediatrician_phone"),
  pediatricianName: text("pediatrician_name"),
  createdAt: timestamp("created_at").defaultNow().notNull(),
  updatedAt: timestamp("updated_at").defaultNow().notNull(),
});

// Family members table
export const familyMembers = pgTable(
  "family_members",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    familyId: uuid("family_id").notNull(),
    userId: uuid("user_id").notNull(),
    role: memberRoleEnum("role").notNull().default("caregiver"),
    createdAt: timestamp("created_at").defaultNow().notNull(),
  },
  (table) => [uniqueIndex("family_members_family_id_user_id_key").on(table.familyId, table.userId)]
);

// Children table
// NOTE (2b): the DB column is `stage`. We keep the JS-friendly key
// `currentStage` mapped onto it so application code reads naturally.
export const children = pgTable(
  "children",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    familyId: uuid("family_id").notNull(),
    name: text("name").notNull(),
    birthDate: date("birth_date").notNull(),
    sex: childSexEnum("sex"), // nullable in prod
    currentStage: childStageEnum("stage").notNull().default("newborn"),
    imageUrl: text("image_url"),
    createdAt: timestamp("created_at").defaultNow().notNull(),
    updatedAt: timestamp("updated_at").defaultNow().notNull(),
  },
  (table) => [index("children_family_idx").on(table.familyId)]
);

// Family invites table
export const familyInvites = pgTable(
  "family_invites",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    familyId: uuid("family_id").notNull(),
    email: text("email").notNull(),
    role: memberRoleEnum("role").notNull().default("viewer"),
    token: text("token").notNull().unique(),
    expiresAt: timestamp("expires_at").notNull(),
    createdAt: timestamp("created_at").defaultNow().notNull(),
  },
  (table) => [uniqueIndex("invite_token_idx").on(table.token)]
);

// Type exports
export type Family = typeof families.$inferSelect;
export type FamilyMember = typeof familyMembers.$inferSelect;
export type Child = typeof children.$inferSelect;
export type FamilyInvite = typeof familyInvites.$inferSelect;

// Helper function for deriving stage
export function deriveStage(birthDate: Date): (typeof childStageEnum)["enumValues"][number] {
  const now = new Date();
  const months = Math.floor(
    (now.getTime() - birthDate.getTime()) / (1000 * 60 * 60 * 24 * 30)
  );

  if (months < 3) return "newborn";
  if (months < 6) return "infant";
  if (months < 12) return "solids_start";
  if (months < 24) return "toddler_early";
  if (months < 36) return "toddler_late";
  return "preschool";
}
