import { pgTable, text, timestamp, index, uniqueIndex } from 'drizzle-orm/pg-core';
import { sql } from 'drizzle-orm';
import { ports } from './ports';
import { berths } from './berths';
import { clients } from './clients';
import { yachts } from './yachts';
import { interests } from './interests';
import { files } from './documents';

export const berthReservations = pgTable(
  'berth_reservations',
  {
    id: text('id')
      .primaryKey()
      .$defaultFn(() => crypto.randomUUID()),
    // H-01: reservations are the canonical "who occupies a berth right
    // now" record; RESTRICT on every parent FK keeps an ad-hoc DB-side
    // hard-delete from leaving a reservation pointing at a missing
    // berth/client/yacht. Interest is nullable + SET NULL because a
    // reservation legitimately outlives the originating deal.
    berthId: text('berth_id')
      .notNull()
      .references(() => berths.id, { onDelete: 'restrict' }),
    portId: text('port_id')
      .notNull()
      .references(() => ports.id, { onDelete: 'restrict' }),
    clientId: text('client_id')
      .notNull()
      .references(() => clients.id, { onDelete: 'restrict' }),
    yachtId: text('yacht_id')
      .notNull()
      .references(() => yachts.id, { onDelete: 'restrict' }),
    interestId: text('interest_id').references(() => interests.id, { onDelete: 'set null' }),
    status: text('status').notNull(), // 'pending' | 'active' | 'ended' | 'cancelled'
    startDate: timestamp('start_date', { withTimezone: true, mode: 'date' }).notNull(),
    endDate: timestamp('end_date', { withTimezone: true, mode: 'date' }),
    // M-L01: canonical tenure_type union is
    // `permanent | fixed_term | fee_simple | strata_lot | seasonal`
    // (kept in sync with berths.tenure_type). 'seasonal' is reservation-
    // specific (winter haul-out etc.); the others mirror the berth's
    // own tenure shape. Configurable via the per-port vocabulary at
    // /admin/vocabularies (key: berth_tenure_types).
    tenureType: text('tenure_type').notNull().default('permanent'),
    contractFileId: text('contract_file_id').references(() => files.id, { onDelete: 'set null' }),
    notes: text('notes'),
    createdBy: text('created_by').notNull(),
    createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
    updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
  },
  (table) => [
    index('idx_br_berth').on(table.berthId),
    index('idx_br_client').on(table.clientId),
    index('idx_br_yacht').on(table.yachtId),
    index('idx_br_port').on(table.portId),
    // Cover the FKs Postgres doesn't auto-index. Without these, deleting
    // (or restrict-checking) the parent interest / contract file row
    // requires a full scan of berth_reservations. (idx_br_interest is
    // already used by berth_recommendations — namespace this one.)
    index('idx_brr_interest').on(table.interestId),
    index('idx_brr_contract_file').on(table.contractFileId),
    uniqueIndex('idx_br_active')
      .on(table.berthId)
      .where(sql`${table.status} = 'active'`),
  ],
);

export type BerthReservation = typeof berthReservations.$inferSelect;
export type NewBerthReservation = typeof berthReservations.$inferInsert;
