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

export enum ActivityType {
  FEEDING = 'feeding',
  SLEEP = 'sleep',
  DIAPER = 'diaper',
  GROWTH = 'growth',
  MEDICATION = 'medication',
  MEDICINE = 'medicine',
  TEMPERATURE = 'temperature',
  MILESTONE = 'milestone',
  ACTIVITY = 'activity',
}

@Entity('activities')
export class Activity {
  @PrimaryColumn({ length: 20 })
  id: string;

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

  @Column({
    type: 'varchar',
    length: 20,
    enum: ActivityType,
  })
  type: ActivityType;

  @Column({ name: 'started_at', type: 'timestamp' })
  startedAt: Date;

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

  @Column({ name: 'logged_by', length: 20 })
  loggedBy: string;

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

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

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

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

  // Relations
  @ManyToOne(() => Child, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'child_id' })
  child: Child;

  @ManyToOne(() => User)
  @JoinColumn({ name: 'logged_by' })
  logger: User;

  @BeforeInsert()
  generateId() {
    if (!this.id) {
      this.id = `act_${nanoid(16)}`;
    }
  }
}
