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

export enum PhotoType {
  MILESTONE = 'milestone',
  ACTIVITY = 'activity',
  PROFILE = 'profile',
  GENERAL = 'general',
}

@Entity('photos')
@Index(['childId', 'createdAt'])
@Index(['activityId'])
export class Photo {
  @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({ name: 'activity_id', length: 20, nullable: true })
  activityId: string | null;

  @ManyToOne(() => Activity, { nullable: true, onDelete: 'SET NULL' })
  @JoinColumn({ name: 'activity_id' })
  activity: Activity | null;

  @Column({
    type: 'varchar',
    length: 20,
    enum: PhotoType,
    default: PhotoType.GENERAL,
  })
  type: PhotoType;

  @Column({ name: 'original_filename', type: 'varchar', length: 255 })
  originalFilename: string;

  @Column({ name: 'mime_type', type: 'varchar', length: 100 })
  mimeType: string;

  @Column({ name: 'file_size', type: 'integer' })
  fileSize: number;

  @Column({ name: 'storage_key', type: 'varchar', length: 255 })
  storageKey: string;

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

  @Column({ type: 'integer', nullable: true })
  width: number | null;

  @Column({ type: 'integer', nullable: true })
  height: number | null;

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

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

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

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

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

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

  @BeforeInsert()
  generateId() {
    if (!this.id) {
      this.id = `pho_${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;
  }
}
