/**
 * Payment gateway config schema — payment-gateway-adapters (wave-10 leaf 5).
 * Postgres / Neon via Hyperdrive.
 *
 * Tables:
 * - payment_gateway_configs: per-tenant gateway selection + encrypted credentials.
 *
 * Supported gateways: cardcom | payplus | stripe
 *
 * DB conventions:
 * - UUID PK .defaultRandom()
 * - TIMESTAMPTZ via timestamp(col, { withTimezone: true })
 * - Enums: text() + check(... IN (...)) — NEVER pgEnum
 * - Credentials: AES-256-GCM via encryptCredential from @zync/utils;
 *   stored as JSON.stringify({ciphertext, iv, authTag}) in encrypted_config.
 *   NEVER store payment credentials in plaintext.
 */
import {
  pgTable,
  uuid,
  text,
  boolean,
  timestamp,
  index,
  check,
  unique,
} from 'drizzle-orm/pg-core'
import { sql } from 'drizzle-orm'
import { tenants } from './tenants'

export const PAYMENT_GATEWAYS = ['cardcom', 'payplus', 'stripe'] as const
export type PaymentGateway = (typeof PAYMENT_GATEWAYS)[number]

// ── payment_gateway_configs ────────────────────────────────────────────────────

export const paymentGatewayConfigs = pgTable(
  'payment_gateway_configs',
  {
    id: uuid('id').primaryKey().defaultRandom(),
    tenantId: uuid('tenant_id')
      .notNull()
      .references(() => tenants.id, { onDelete: 'cascade' }),
    gateway: text('gateway').notNull(),
    // JSON.stringify({ ciphertext, iv, authTag }) from encryptCredential
    encryptedConfig: text('encrypted_config').notNull(),
    isActive: boolean('is_active').default(false).notNull(),
    testMode: boolean('test_mode').default(true).notNull(),
    createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
    updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
  },
  (t) => ({
    tenantUniq: unique('payment_gateway_configs_tenant_unique').on(t.tenantId),
    tenantIdx: index('idx_payment_gateway_configs_tenant').on(t.tenantId),
    gatewayCheck: check(
      'payment_gateway_configs_gateway_check',
      sql`${t.gateway} IN ('cardcom','payplus','stripe')`,
    ),
  }),
)

export type PaymentGatewayConfigRow = typeof paymentGatewayConfigs.$inferSelect
export type NewPaymentGatewayConfig = typeof paymentGatewayConfigs.$inferInsert
