import { jsonb, pgTable, text, timestamp, uniqueIndex } from "drizzle-orm/pg-core";
import { intId, intPk } from "./columns";
import { users } from "./identity";

/**
 * User-level third-party connections: Google Calendar, Outlook, Zoom OAuth,
 * and optional BYOK OpenAI API key. Tokens/secrets are stored encrypted
 * (AES-GCM) as opaque ciphertext — never returned to the client in full.
 */
export const userIntegrations = pgTable(
  "user_integrations",
  {
    id: intPk(),
    userId: intId("user_id")
      .notNull()
      .references(() => users.id, { onDelete: "cascade" }),
    /** google_calendar | outlook_calendar | zoom | openai */
    provider: text("provider").notNull(),
    /** Encrypted access token (OAuth) or API key (openai). */
    accessTokenEnc: text("access_token_enc"),
    /** Encrypted refresh token when the provider issues one. */
    refreshTokenEnc: text("refresh_token_enc"),
    accessTokenExpiresAt: timestamp("access_token_expires_at", { withTimezone: true }),
    scopes: text("scopes"),
    accountEmail: text("account_email"),
    accountLabel: text("account_label"),
    /** Last 4 chars of an API key for display (openai). */
    secretLast4: text("secret_last4"),
    metadata: jsonb("metadata").notNull().default({}),
    createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
    updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
  },
  (t) => [uniqueIndex("user_integrations_user_provider_idx").on(t.userId, t.provider)],
);
