/**
 * NotificationBatch Entity
 * Batch notification campaigns with audience targeting
 * Compatible with erp-core notification-batch.entity
 *
 * @module Notifications
 */

import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  Index,
  ManyToOne,
  JoinColumn,
} from 'typeorm';
import { NotificationTemplate } from './template.entity';
import { ChannelType } from './channel.entity';

export type BatchStatus = 'draft' | 'scheduled' | 'processing' | 'completed' | 'failed' | 'cancelled';
export type AudienceType = 'all_users' | 'segment' | 'custom';

@Entity({ name: 'notification_batches', schema: 'notifications' })
export class NotificationBatch {
  @PrimaryGeneratedColumn('uuid')
  id: string;

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

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

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

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

  @Column({ name: 'channel_type', type: 'varchar', length: 30 })
  channelType: ChannelType;

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

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

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

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

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

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

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

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

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

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

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

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

  @ManyToOne(() => NotificationTemplate, { onDelete: 'SET NULL', nullable: true })
  @JoinColumn({ name: 'template_id' })
  template: NotificationTemplate | null;

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