import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  Index,
  ManyToOne,
  JoinColumn,
} from 'typeorm';
import { ReportSchedule, ScheduleExecutionStatus } from './report-schedule.entity';
import { ReportExecution } from './report-execution.entity';

/**
 * Schedule Execution Entity (schema: reports.schedule_executions)
 *
 * Links scheduled reports to their actual executions,
 * tracking delivery status and recipient notifications.
 */
@Entity({ name: 'schedule_executions', schema: 'reports' })
export class ScheduleExecution {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Index()
  @Column({ name: 'schedule_id', type: 'uuid' })
  scheduleId: string;

  @Column({ name: 'execution_id', type: 'uuid', nullable: true })
  executionId: string | null;

  @Column({
    name: 'status',
    type: 'enum',
    enum: ScheduleExecutionStatus,
    enumName: 'schedule_execution_status',
  })
  status: ScheduleExecutionStatus;

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

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

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

  @Index()
  @Column({ name: 'executed_at', type: 'timestamptz', default: () => 'CURRENT_TIMESTAMP' })
  executedAt: Date;

  // Relations
  @ManyToOne(() => ReportSchedule, (schedule) => schedule.scheduleExecutions, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'schedule_id' })
  schedule: ReportSchedule;

  @ManyToOne(() => ReportExecution, { onDelete: 'SET NULL' })
  @JoinColumn({ name: 'execution_id' })
  execution: ReportExecution | null;
}
