import {
  Entity,
  Column,
  PrimaryColumn,
  CreateDateColumn,
  UpdateDateColumn,
  ManyToOne,
  JoinColumn,
  BeforeInsert,
  Index,
} from 'typeorm';
import { User } from './user.entity';
import { Child } from './child.entity';

export enum NotificationType {
  FEEDING_REMINDER = 'feeding_reminder',
  SLEEP_REMINDER = 'sleep_reminder',
  DIAPER_REMINDER = 'diaper_reminder',
  MEDICATION_REMINDER = 'medication_reminder',
  MILESTONE_ALERT = 'milestone_alert',
  GROWTH_TRACKING = 'growth_tracking',
  APPOINTMENT_REMINDER = 'appointment_reminder',
  PATTERN_ANOMALY = 'pattern_anomaly',
}

export enum NotificationStatus {
  PENDING = 'pending',
  SENT = 'sent',
  READ = 'read',
  DISMISSED = 'dismissed',
  FAILED = 'failed',
}

export enum NotificationPriority {
  LOW = 'low',
  MEDIUM = 'medium',
  HIGH = 'high',
  URGENT = 'urgent',
}

@Entity('notifications')
@Index(['userId', 'status', 'createdAt'])
@Index(['childId', 'type'])
export class Notification {
  @PrimaryColumn({ length: 20 })
  id: string;

  @Column({ name: 'user_id', length: 20 })
  userId: string;

  @ManyToOne(() => User, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'user_id' })
  user: User;

  @Column({ name: 'child_id', length: 20, nullable: true })
  childId: string | null;

  @ManyToOne(() => Child, { nullable: true, onDelete: 'CASCADE' })
  @JoinColumn({ name: 'child_id' })
  child: Child | null;

  @Column({
    type: 'varchar',
    length: 50,
    enum: NotificationType,
  })
  type: NotificationType;

  @Column({
    type: 'varchar',
    length: 20,
    enum: NotificationStatus,
    default: NotificationStatus.PENDING,
  })
  status: NotificationStatus;

  @Column({
    type: 'varchar',
    length: 20,
    enum: NotificationPriority,
    default: NotificationPriority.MEDIUM,
  })
  priority: NotificationPriority;

  @Column({ type: 'varchar', length: 255 })
  title: string;

  @Column({ type: 'text' })
  message: string;

  @Column({ type: 'jsonb', nullable: true })
  metadata: {
    estimatedTime?: string;
    reason?: string;
    activityType?: string;
    milestoneType?: string;
    [key: string]: any;
  } | null;

  @Column({ name: 'scheduled_for', type: 'timestamp', nullable: true })
  scheduledFor: Date | null;

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

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

  @Column({ name: 'dismissed_at', type: 'timestamp', nullable: true })
  dismissedAt: Date | null;

  @Column({
    name: 'device_token',
    type: 'varchar',
    length: 255,
    nullable: true,
  })
  deviceToken: string | null;

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

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

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

  @BeforeInsert()
  generateId() {
    if (!this.id) {
      this.id = `ntf_${this.generateNanoId()}`;
    }
  }

  private generateNanoId(): string {
    const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
    let result = '';
    for (let i = 0; i < 12; i++) {
      result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return result;
  }
}
