import {
  Column,
  CreateDateColumn,
  Entity,
  Index,
  JoinColumn,
  ManyToMany,
  ManyToOne,
  PrimaryGeneratedColumn,
  UpdateDateColumn,
} from 'typeorm';
import { User } from '../../entities/user.entity';
import { AiMessage } from './ai-message.entity';

export type AiAttachmentStatus = 'processing' | 'ready' | 'failed';

@Entity('ai_attachments')
@Index('idx_ai_attachments_user_created', ['userId', 'createdAt'])
export class AiAttachment {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ name: 'user_id', type: 'integer' })
  userId: number;

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

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

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

  @Column({ type: 'integer' })
  size: number;

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

  @Column({ name: 'processing_status', type: 'varchar', length: 20, default: 'processing' })
  processingStatus: AiAttachmentStatus;

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

  @Column({ name: 'processing_error', type: 'varchar', length: 200, nullable: true })
  processingError: string | null;

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

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

  @ManyToMany(() => AiMessage, (message) => message.attachments)
  messages: AiMessage[];

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

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