import {
  bigserial,
  boolean,
  text,
  timestamp,
  pgTable,
  bigint,
  index,
  unique,
} from "drizzle-orm/pg-core";
import { user } from "./users";
import { InferModel } from "drizzle-orm";

// Current approval state per (deal, measure) — upserted on each change.
// Query WHERE is_approved = true to get the currently approved set.
export const dealMeasureApprovals = pgTable(
  "deal_measure_approvals",
  {
    id: bigserial("id", { mode: "bigint" }).primaryKey(),
    hubspotDealId: text("hubspot_deal_id").notNull(),
    measureName: text("measure_name").notNull(),
    isApproved: boolean("is_approved").notNull().default(true),
    approvedBy: bigint("approved_by", { mode: "bigint" })
      .notNull()
      .references(() => user.id),
    approvedAt: timestamp("approved_at", { withTimezone: true })
      .defaultNow()
      .notNull(),
  },
  (table) => [
    unique("uq_deal_measure").on(table.hubspotDealId, table.measureName),
    index("idx_deal_measure_approvals_deal_id").on(table.hubspotDealId),
  ],
);

// Append-only audit log — never deleted.
export const dealMeasureApprovalEvents = pgTable(
  "deal_measure_approval_events",
  {
    id: bigserial("id", { mode: "bigint" }).primaryKey(),
    hubspotDealId: text("hubspot_deal_id").notNull(),
    measureName: text("measure_name").notNull(),
    // 'approved' | 'unapproved'
    action: text("action").notNull(),
    actedBy: bigint("acted_by", { mode: "bigint" })
      .notNull()
      .references(() => user.id),
    actedAt: timestamp("acted_at", { withTimezone: true })
      .defaultNow()
      .notNull(),
  },
  (table) => [
    index("idx_deal_measure_events_deal_id").on(table.hubspotDealId),
    index("idx_deal_measure_events_acted_at").on(table.actedAt),
  ],
);

export type DealMeasureApproval = InferModel<
  typeof dealMeasureApprovals,
  "select"
>;
export type DealMeasureApprovalEvent = InferModel<
  typeof dealMeasureApprovalEvents,
  "select"
>;
