/**
 * User-defined deal measures (issue #253)
 *
 * Tracks measures that an approver has *instructed* outside the coordinator's
 * proposed set, plus measures that have been *PIBI-ordered* by the contractor
 * (slice 4). The `source` enum distinguishes the two flows so a single table
 * can back both.
 *
 * Each row pushes back to HubSpot under one of two new multi-value text deal
 * properties (`instructed_measures` / `pibi_ordered_measures`). `pushed_at`
 * is stamped after a successful sync; `confirmed_in_hubspot_at` is stamped
 * by a follow-up reconcile job (out of scope for this slice).
 */
import {
  bigserial,
  text,
  timestamp,
  pgTable,
  bigint,
  index,
  pgEnum,
} from "drizzle-orm/pg-core";
import { user } from "./users";
import { InferModel } from "drizzle-orm";

export const UserDefinedDealMeasureSource: [string, ...string[]] = [
  "instructed",
  "pibi_ordered",
];
export type UserDefinedDealMeasureSourceType =
  | "instructed"
  | "pibi_ordered";

export const userDefinedDealMeasureSourceEnum = pgEnum(
  "user_defined_deal_measure_source",
  UserDefinedDealMeasureSource as [string, ...string[]],
);

export const userDefinedDealMeasures = pgTable(
  "user_defined_deal_measures",
  {
    id: bigserial("id", { mode: "bigint" }).primaryKey(),
    hubspotDealId: text("hubspot_deal_id").notNull(),
    measureName: text("measure_name").notNull(),
    source: userDefinedDealMeasureSourceEnum("source").notNull(),
    createdByUserId: bigint("created_by_user_id", { mode: "bigint" })
      .notNull()
      .references(() => user.id),
    createdAt: timestamp("created_at", { withTimezone: true })
      .defaultNow()
      .notNull(),
    pushedAt: timestamp("pushed_at", { withTimezone: true }),
    confirmedInHubspotAt: timestamp("confirmed_in_hubspot_at", {
      withTimezone: true,
    }),
    notes: text("notes"),
  },
  (table) => [
    index("idx_user_defined_deal_measures_deal_id").on(table.hubspotDealId),
    index("idx_user_defined_deal_measures_source").on(table.source),
  ],
);

export type UserDefinedDealMeasure = InferModel<
  typeof userDefinedDealMeasures,
  "select"
>;
