import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  OneToMany,
  ManyToOne,
  JoinColumn,
  Unique,
} from 'typeorm';
import { Definition } from './definition.entity';
import { User } from '../../auth/entities/user.entity';

/** Lifecycle status of a word */
export type WordStatus = 'active' | 'to_be_defined';

/**
 * Word entity — the core concept of LexiBrain.
 * Each word belongs to a user — two users can have the same word independently.
 * The composite unique constraint (text, ownerId) enforces uniqueness per user.
 */
@Entity('word')
@Unique(['text', 'ownerId'])
export class Word {
  @PrimaryGeneratedColumn('uuid')
  id!: string;

  /** The word or phrase itself — unique per user */
  @Column({ type: 'varchar', length: 255 })
  text!: string;

  /** Timestamp set automatically on insert */
  @CreateDateColumn()
  createdAt!: Date;

  /**
   * 'active'        — the word has at least one definition.
   * 'to_be_defined' — the word was created without a definition.
   */
  @Column({ type: 'varchar', length: 20, default: 'active' })
  status!: WordStatus;

  /** The user who owns this word */
  @Column({ type: 'varchar', length: 36, nullable: true })
  ownerId!: string | null;

  @ManyToOne(() => User, { nullable: true, onDelete: 'CASCADE' })
  @JoinColumn({ name: 'owner_id' })
  owner!: User | null;

  /** A word can have multiple definitions ordered by date */
  @OneToMany(() => Definition, (definition) => definition.word, {
    cascade: true,
  })
  definitions!: Definition[];
}
