import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  Index,
  ManyToOne,
  JoinColumn,
} from 'typeorm';
import { WhatsAppAccount } from './account.entity';

export type AutomationTriggerType = 'keyword' | 'first_message' | 'after_hours' | 'no_response' | 'webhook';
export type AutomationActionType = 'send_message' | 'send_template' | 'assign_agent' | 'add_tag' | 'create_ticket';

@Entity({ name: 'automations', schema: 'whatsapp' })
export class WhatsAppAutomation {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Index()
  @Column({ name: 'tenant_id', type: 'uuid' })
  tenantId: string;

  @Index()
  @Column({ name: 'account_id', type: 'uuid' })
  accountId: string;

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

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

  @Column({ name: 'trigger_type', type: 'varchar', length: 30 })
  triggerType: AutomationTriggerType;

  @Column({ name: 'trigger_config', type: 'jsonb', default: {} })
  triggerConfig: Record<string, any>;

  @Column({ name: 'action_type', type: 'varchar', length: 30 })
  actionType: AutomationActionType;

  @Column({ name: 'action_config', type: 'jsonb', default: {} })
  actionConfig: Record<string, any>;

  @Column({ name: 'conditions', type: 'jsonb', default: [] })
  conditions: Record<string, any>[];

  @Index()
  @Column({ name: 'is_active', type: 'boolean', default: true })
  isActive: boolean;

  @Column({ name: 'priority', type: 'int', default: 0 })
  priority: number;

  @Column({ name: 'trigger_count', type: 'int', default: 0 })
  triggerCount: number;

  @Column({ name: 'last_triggered_at', type: 'timestamptz', nullable: true })
  lastTriggeredAt: Date;

  @CreateDateColumn({ name: 'created_at', type: 'timestamptz' })
  createdAt: Date;

  @UpdateDateColumn({ name: 'updated_at', type: 'timestamptz' })
  updatedAt: Date;

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

  @ManyToOne(() => WhatsAppAccount, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'account_id' })
  account: WhatsAppAccount;
}
