import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  Index,
  ManyToOne,
  JoinColumn,
  Unique,
} from 'typeorm';
import { Broadcast } from './broadcast.entity';
import { WhatsAppContact } from './contact.entity';
import { WhatsAppMessage } from './message.entity';

export type RecipientStatus = 'pending' | 'sent' | 'delivered' | 'read' | 'failed';

@Entity({ name: 'broadcast_recipients', schema: 'whatsapp' })
@Unique(['broadcastId', 'contactId'])
export class BroadcastRecipient {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Index()
  @Column({ name: 'broadcast_id', type: 'uuid' })
  broadcastId: string;

  @Column({ name: 'contact_id', type: 'uuid' })
  contactId: string;

  @Column({ name: 'template_variables', type: 'jsonb', default: [] })
  templateVariables: any[];

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

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

  @Column({ name: 'error_code', type: 'varchar', length: 20, nullable: true })
  errorCode: string;

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

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

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

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

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

  @ManyToOne(() => Broadcast, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'broadcast_id' })
  broadcast: Broadcast;

  @ManyToOne(() => WhatsAppContact, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'contact_id' })
  contact: WhatsAppContact;

  @ManyToOne(() => WhatsAppMessage, { nullable: true })
  @JoinColumn({ name: 'message_id' })
  message: WhatsAppMessage;
}
