import type { QueryResult as PgQueryResult, PoolClient, QueryResultRow } from 'pg';

/**
 * PostgreSQL Client Configuration
 */
export interface PostgreSQLClientConfig {
  host: string;
  port: number;
  database: string;
  username: string;
  password: string;
  poolSettings?: {
    min: number;
    max: number;
    idleTimeoutMillis: number;
  };
  ssl?: {
    enabled: boolean;
    rejectUnauthorized: boolean;
  };
  timeouts?: {
    query: number;
    connection: number;
    statement: number;
    lock: number;
    idleInTransaction: number;
  };
}

/**
 * PostgreSQL Connection Options
 */
export interface PostgreSQLConnectionOptions {
  retryAttempts?: number;
  retryDelay?: number;
  healthCheckInterval?: number;
}

export interface PoolMetrics {
  totalConnections: number;
  activeConnections: number;
  idleConnections: number;
  waitingRequests: number;
  errors: number;
  lastError?: string;
  avgResponseTime?: number;
  created: Date;
  lastUsed?: Date;
}

export interface ConnectionEvents {
  onConnect?: () => void | Promise<void>;
  onDisconnect?: () => void | Promise<void>;
  onError?: (error: Error) => void | Promise<void>;
  onPoolCreated?: () => void | Promise<void>;
}

export interface DynamicPoolConfig {
  enabled: boolean;
  minSize: number;
  maxSize: number;
  scaleUpThreshold: number; // % of pool in use (0-100)
  scaleDownThreshold: number; // % of pool idle (0-100)
  scaleUpIncrement: number; // connections to add
  scaleDownIncrement: number; // connections to remove
  evaluationInterval: number; // ms between checks
}

/**
 * Health Status Types
 */
export type PostgreSQLHealthStatus = 'healthy' | 'degraded' | 'unhealthy';

export interface PostgreSQLHealthCheck {
  status: PostgreSQLHealthStatus;
  timestamp: Date;
  latency: number;
  connections: {
    active: number;
    idle: number;
    total: number;
  };
  errors?: string[];
}

export interface PostgreSQLMetrics {
  queriesPerSecond: number;
  averageQueryTime: number;
  errorRate: number;
  connectionPoolUtilization: number;
  slowQueries: number;
}

/**
 * Query Result Types
 */
export interface QueryResult<T extends QueryResultRow = any> extends PgQueryResult<T> {
  executionTime?: number;
}

export type TransactionCallback<T> = (client: PoolClient) => Promise<T>;

/**
 * Schema and Table Names
 */
export type SchemaNames = 'trading' | 'strategy' | 'risk' | 'audit';

export type TableNames =
  | 'trades'
  | 'orders'
  | 'positions'
  | 'portfolios'
  | 'strategies'
  | 'risk_limits'
  | 'audit_logs'
  | 'users'
  | 'accounts'
  | 'symbols'
  | 'exchanges';

/**
 * Trading Domain Types
 */
export interface Trade {
  id: string;
  order_id: string;
  symbol: string;
  side: 'buy' | 'sell';
  quantity: number;
  price: number;
  executed_at: Date;
  commission: number;
  fees: number;
  portfolio_id: string;
  strategy_id?: string;
  created_at: Date;
  updated_at: Date;
}

export interface Order {
  id: string;
  symbol: string;
  side: 'buy' | 'sell';
  type: 'market' | 'limit' | 'stop' | 'stop_limit';
  quantity: number;
  price?: number;
  stop_price?: number;
  status: 'pending' | 'filled' | 'cancelled' | 'rejected';
  portfolio_id: string;
  strategy_id?: string;
  created_at: Date;
  updated_at: Date;
  expires_at?: Date;
}

export interface Position {
  id: string;
  symbol: string;
  quantity: number;
  average_cost: number;
  market_value: number;
  unrealized_pnl: number;
  realized_pnl: number;
  portfolio_id: string;
  created_at: Date;
  updated_at: Date;
}

export interface Portfolio {
  id: string;
  name: string;
  cash_balance: number;
  total_value: number;
  unrealized_pnl: number;
  realized_pnl: number;
  user_id: string;
  created_at: Date;
  updated_at: Date;
}

export interface Strategy {
  id: string;
  name: string;
  description: string;
  parameters: Record<string, any>;
  status: 'active' | 'inactive' | 'paused';
  performance_metrics: Record<string, number>;
  portfolio_id: string;
  created_at: Date;
  updated_at: Date;
}

export interface RiskLimit {
  id: string;
  type: 'position_size' | 'daily_loss' | 'max_drawdown' | 'concentration';
  value: number;
  threshold: number;
  status: 'active' | 'breached' | 'disabled';
  portfolio_id?: string;
  strategy_id?: string;
  created_at: Date;
  updated_at: Date;
}

export interface AuditLog {
  id: string;
  action: string;
  entity_type: string;
  entity_id: string;
  old_values?: Record<string, any>;
  new_values?: Record<string, any>;
  user_id?: string;
  ip_address?: string;
  user_agent?: string;
  timestamp: Date;
}

/**
 * Query Builder Types
 */
export interface WhereCondition {
  column: string;
  operator:
    | '='
    | '!='
    | '>'
    | '<'
    | '>='
    | '<='
    | 'IN'
    | 'NOT IN'
    | 'LIKE'
    | 'ILIKE'
    | 'IS NULL'
    | 'IS NOT NULL';
  value?: any;
}

export interface JoinCondition {
  type: 'INNER' | 'LEFT' | 'RIGHT' | 'FULL';
  table: string;
  on: string;
}

export interface OrderByCondition {
  column: string;
  direction: 'ASC' | 'DESC';
}
