/**
 * Billing: plans, add_ons, brand_add_ons.
 * Source: `db/migrations/0001_init.sql`.
 */
import {
  pgTable,
  uuid,
  text,
  integer,
  timestamp,
  jsonb,
  primaryKey,
} from "drizzle-orm/pg-core";
import { brands } from "./brands";

export const plans = pgTable("plans", {
  id: uuid("id").primaryKey().defaultRandom(),
  code: text("code", {
    enum: ["starter", "farm", "enterprise"],
  }).notNull().unique(),
  name: text("name").notNull(),
  monthlyPriceCents: integer("monthly_price_cents").notNull(),
  maxUsers: integer("max_users").notNull(),
  maxProducts: integer("max_products").notNull(),
  maxStopsMonthly: integer("max_stops_monthly").notNull(),
  features: jsonb("features").notNull().default([]),
  createdAt: timestamp("created_at", { withTimezone: true })
    .notNull()
    .defaultNow(),
});

export const addOns = pgTable("add_ons", {
  id: uuid("id").primaryKey().defaultRandom(),
  code: text("code", {
    enum: [
      "wholesale_portal", "harvest_reach", "ai_tools",
      "water_log", "square_sync", "sms_campaigns",
    ],
  }).notNull().unique(),
  name: text("name").notNull(),
  monthlyPriceCents: integer("monthly_price_cents").notNull(),
  description: text("description"),
  createdAt: timestamp("created_at", { withTimezone: true })
    .notNull()
    .defaultNow(),
});

export const brandAddOns = pgTable(
  "brand_add_ons",
  {
    brandId: uuid("brand_id")
      .notNull()
      .references(() => brands.id, { onDelete: "cascade" }),
    addOnId: uuid("add_on_id")
      .notNull()
      .references(() => addOns.id, { onDelete: "cascade" }),
    stripeSubscriptionId: text("stripe_subscription_id"),
    status: text("status", { enum: ["active", "canceled"] })
      .notNull()
      .default("active"),
    createdAt: timestamp("created_at", { withTimezone: true })
      .notNull()
      .defaultNow(),
  },
  (t) => ({
    pk: primaryKey({ columns: [t.brandId, t.addOnId] }),
  }),
);

export type Plan = typeof plans.$inferSelect;
export type AddOn = typeof addOns.$inferSelect;
export type BrandAddOn = typeof brandAddOns.$inferSelect;
