import { pgTable, serial, boolean, text, timestamp, jsonb, check } from 'drizzle-orm/pg-core';
import { sql } from 'drizzle-orm';

// The integrations the server knows how to configure. `provider` was free text, which is how rows for
// telegram, whatsapp and discord went on holding bot tokens long after the code that read them was
// deleted — nothing structural said they were no longer legal.
//
// Adding an integration means adding it here. That is the point: the schema is the source of truth for
// what may exist, so a provider the code no longer supports cannot sit in the table unnoticed.
const SERVER_PROVIDERS = ['google', 'apify'] as const;

export const serverConfig = pgTable('server_config', {
  key: text('key').primaryKey(),
  value: jsonb('value').notNull(),
  updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
});

export const serverIntegrations = pgTable(
  'server_integrations',
  {
    id: serial('id').primaryKey(),
    provider: text('provider').notNull().unique(),
    enabled: boolean('enabled').notNull().default(true),
    config: jsonb('config').notNull().default({}),
    createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
    updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
  },
  (table) => [
    check(
      'ck_server_integrations_provider',
      // sql.raw, not `sql`${p}``: interpolating a JS string binds it as a parameter, so the constraint
      // is emitted as `IN ($1, $2)` and Postgres rejects it ("there is no parameter $1") — which breaks
      // `bun db:push` for the entire schema, not just this table. Safe because the values are compile-time
      // literals from the const tuple above.
      sql`${table.provider} IN (${sql.join(
        SERVER_PROVIDERS.map((p) => sql.raw(`'${p}'`)),
        sql`, `,
      )})`,
    ),
  ],
);
