import { index, pgTable, text, timestamp, uniqueIndex, uuid } from 'drizzle-orm/pg-core';
import { users } from './identity';

/**
 * Durable source identities make repeated imports updates rather than duplicate
 * creates. Raw spreadsheet content stays out of the database; only the user's
 * chosen stable key and the PIG record it resolved to are retained.
 */
export const importIdentities = pgTable(
  'import_identities',
  {
    id: uuid('id').primaryKey().defaultRandom(),
    entity: text('entity').notNull(),
    keyColumn: text('key_column').notNull(),
    keyValue: text('key_value').notNull(),
    recordId: uuid('record_id').notNull(),
    importedByUserId: uuid('imported_by_user_id').references(() => users.id, {
      onDelete: 'set null',
    }),
    createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
    updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
  },
  (table) => [
    uniqueIndex('import_identities_source_key').on(
      table.entity,
      table.keyColumn,
      table.keyValue,
    ),
    index('import_identities_record_idx').on(table.entity, table.recordId),
  ],
);

export type ImportIdentity = typeof importIdentities.$inferSelect;
