/**
 * Proxies / points-of-contact (CM-9).
 *
 * A `proxy` is a designated contact person who acts on behalf of an entity.
 * Polymorphic: attachable to a `client` (default), an `interest` (per-deal
 * override), or a `yacht` (per-vessel override). At most one proxy per entity
 * (unique index). Outbound comms resolve the most specific proxy via the chain
 * yacht → interest → client (see resolveEffectiveProxy in proxies.service).
 *
 * `entity_id` is polymorphic (no FK) — validated against the right table in the
 * service, same pattern as polymorphic yacht ownership / notes.
 */

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

import { ports } from './ports';

export const proxies = pgTable(
  'proxies',
  {
    id: text('id')
      .primaryKey()
      .$defaultFn(() => crypto.randomUUID()),
    portId: text('port_id')
      .notNull()
      .references(() => ports.id, { onDelete: 'cascade' }),
    /** 'client' | 'interest' | 'yacht' */
    entityType: text('entity_type').notNull(),
    entityId: text('entity_id').notNull(),
    name: text('name').notNull(),
    email: text('email'),
    phone: text('phone'),
    /** Free-form relationship label, e.g. broker / spouse / assistant / legal. */
    relationship: text('relationship'),
    notes: text('notes'),
    createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
    updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
  },
  (table) => [
    // At most one proxy per entity.
    uniqueIndex('uniq_proxies_entity').on(table.portId, table.entityType, table.entityId),
    index('idx_proxies_entity').on(table.entityType, table.entityId),
    index('idx_proxies_port').on(table.portId),
  ],
);

export type Proxy = typeof proxies.$inferSelect;
export type NewProxy = typeof proxies.$inferInsert;
