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

// Port settings type for JSONB column
export type PortSettings = {
  berth_status_rules?: Array<{
    trigger: string;
    mode: 'auto' | 'suggest' | 'off';
    target_status: string;
  }>;
  follow_up_defaults?: {
    reminder_days: number;
    send_window_hours: number[];
    cooldown_days: number;
  };
  eoi_reminder_settings?: {
    schedule: string[];
    cooldown_days: number;
    send_window_hours: number[];
  };
  [key: string]: unknown;
};

export type PortBranding = {
  logo_url?: string;
  primary_color?: string;
  secondary_color?: string;
  font_family?: string;
  [key: string]: unknown;
};

export const ports = pgTable(
  'ports',
  {
    id: text('id')
      .primaryKey()
      .$defaultFn(() => crypto.randomUUID()),
    name: text('name').notNull(),
    slug: text('slug').notNull(),
    logoUrl: text('logo_url'),
    primaryColor: text('primary_color'),
    defaultCurrency: text('default_currency').notNull().default('USD'),
    timezone: text('timezone').notNull().default('America/Anguilla'),
    settings: jsonb('settings').$type<PortSettings>().notNull().default({}),
    isActive: boolean('is_active').notNull().default(true),
    createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
    updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
  },
  (table) => [uniqueIndex('ports_slug_idx').on(table.slug)],
);

export type Port = typeof ports.$inferSelect;
export type NewPort = typeof ports.$inferInsert;
