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

export type BroadcastStatus = 'draft' | 'scheduled' | 'sending' | 'completed' | 'cancelled' | 'failed';
export type AudienceType = 'all' | 'segment' | 'custom' | 'file';

@Entity({ name: 'broadcasts', schema: 'whatsapp' })
export class Broadcast {
  @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: 'template_id', type: 'uuid' })
  templateId: string;

  @Column({ name: 'audience_type', type: 'varchar', length: 30 })
  audienceType: AudienceType;

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

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

  @Index()
  @Column({ name: 'scheduled_at', type: 'timestamptz', nullable: true })
  scheduledAt: Date;

  @Column({ name: 'timezone', type: 'varchar', length: 50, default: 'America/Mexico_City' })
  timezone: string;

  @Index()
  @Column({ name: 'status', type: 'varchar', length: 20, default: 'draft' })
  status: BroadcastStatus;

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

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

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

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

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

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

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

  @Column({ name: 'estimated_cost', type: 'decimal', precision: 10, scale: 2, nullable: true })
  estimatedCost: number;

  @Column({ name: 'actual_cost', type: 'decimal', precision: 10, scale: 2, nullable: true })
  actualCost: number;

  @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;

  @ManyToOne(() => WhatsAppTemplate)
  @JoinColumn({ name: 'template_id' })
  template: WhatsAppTemplate;
}
