import { Entity, PrimaryColumn, Column, CreateDateColumn, UpdateDateColumn } from 'typeorm';

@Entity('standing_orders')
export class StandingOrder {
  @PrimaryColumn({ type: 'varchar', length: 30 })
  id!: string;

  @Column({ type: 'varchar', length: 20 })
  tenantId!: string;

  @Column({ type: 'varchar', length: 200 })
  name!: string;

  @Column({ type: 'text', nullable: true })
  description?: string;

  @Column({ type: 'uuid' })
  definedInSessionId!: string;

  @Column({ type: 'uuid', nullable: true })
  lastModifiedInSessionId?: string;

  @Column({ type: 'varchar', length: 20, name: 'trigger_type' })
  triggerType!: string;

  @Column({ type: 'jsonb', name: 'trigger_config' })
  trigger!: {
    type: 'cron' | 'event' | 'threshold' | 'manual';
    cronExpression?: string;
    eventType?: string;
    thresholdCondition?: {
      metricType: string;
      operator: '>' | '<' | '==' | '>=';
      value: number;
      durationSeconds: number;
    };
  };

  @Column({ type: 'jsonb' })
  targets!: {
    serverIds?: string[];
    clusterIds?: string[];
    allServers?: boolean;
    environmentFilter?: string[];
    tagFilter?: Record<string, string>;
  };

  @Column({ type: 'text', name: 'agent_prompt' })
  agentPrompt!: string;

  @Column({ type: 'varchar', array: true, name: 'agent_skills', nullable: true })
  agentSkills?: string[];

  @Column({ type: 'uuid', nullable: true })
  runbookId?: string;

  @Column({ type: 'smallint', default: 0, name: 'max_risk_level' })
  maxRiskLevel!: 0 | 1;

  @Column({ type: 'int', default: 20, name: 'max_turns' })
  maxTurns!: number;

  @Column({ type: 'numeric', precision: 6, scale: 2, nullable: true, name: 'max_budget_usd' })
  maxBudgetUsd?: number;

  @Column({ type: 'jsonb', name: 'decision_boundary' })
  decisionBoundary!: {
    allowedActions: string[];
    escalateConditions: string[];
    escalationRules: Array<{
      condition: string;
      channel: 'voice_call' | 'im' | 'sms' | 'push' | 'email';
      priority: 'urgent' | 'high' | 'normal' | 'low';
    }>;
  };

  @Column({ type: 'uuid', nullable: true })
  escalationPolicyId?: string;

  @Column({ type: 'varchar', length: 20, default: 'active' })
  status!: 'active' | 'paused' | 'archived';

  @Column({ type: 'timestamptz', name: 'valid_from', default: () => 'NOW()' })
  validFrom!: Date;

  @Column({ type: 'timestamptz', nullable: true, name: 'valid_until' })
  validUntil?: Date;

  @Column({ type: 'uuid', name: 'created_by' })
  createdBy!: string;

  @CreateDateColumn({ type: 'timestamptz' })
  createdAt!: Date;

  @UpdateDateColumn({ type: 'timestamptz' })
  updatedAt!: Date;
}
