import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  DeleteDateColumn,
  ManyToOne,
  JoinColumn,
} from 'typeorm';
import { User } from './user.entity';
import { TemplateFormSection } from './template-form-section.entity';
import { MasterQuestion } from './master-question.entity';
import { QuestionType } from '../enum/question-type.enum';
import { AnswerType } from '../enum/answer-type.enum';

@Entity('template_question')
export class TemplateQuestion {
  @PrimaryGeneratedColumn({ type: 'bigint' })
  id: number;

  @Column({ name: 'template_form_section_id', type: 'bigint' })
  templateFormSectionId: number;

  @ManyToOne(() => TemplateFormSection, (section) => section.questions, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'template_form_section_id' })
  templateFormSection: TemplateFormSection;

  @Column({ name: 'master_question_id', type: 'bigint', nullable: true })
  masterQuestionId: number | null;

  @ManyToOne(() => MasterQuestion, { nullable: true, onDelete: 'SET NULL' })
  @JoinColumn({ name: 'master_question_id' })
  masterQuestion: MasterQuestion;

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

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

  @Column({ name: 'question_text', type: 'text' })
  questionText: string;

  @Column({
    name: 'question_type',
    type: 'enum',
    enum: QuestionType,
  })
  questionType: QuestionType;

  @Column({
    name: 'answer_type',
    type: 'enum',
    enum: AnswerType,
  })
  answerType: AnswerType;

  @Column({ name: 'answer_location', type: 'varchar', length: 1024, nullable: true })
  answerLocation: string | null;

  @Column({ name: 'option_config', type: 'jsonb', nullable: true })
  optionConfig: Record<string, any>[] | null;

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

  @Column({ name: 'conditional_config', type: 'jsonb', nullable: true })
  conditionalConfig: Record<string, any> | null;

  @Column({ name: 'display_order', type: 'int' })
  displayOrder: number;

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

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

  @DeleteDateColumn({ name: 'deleted_at', type: 'timestamptz', nullable: true })
  deletedAt: Date | null;

  @Column({ name: 'created_by', type: 'int', nullable: true })
  createdBy: number | null;

  @Column({ name: 'updated_by', type: 'int', nullable: true })
  updatedBy: number | null;

  @ManyToOne(() => User, { nullable: true, onDelete: 'SET NULL' })
  @JoinColumn({ name: 'created_by' })
  createdByUser: User;

  @ManyToOne(() => User, { nullable: true, onDelete: 'SET NULL' })
  @JoinColumn({ name: 'updated_by' })
  updatedByUser: User;

  constructor(partial: Partial<TemplateQuestion>) {
    Object.assign(this, partial);
  }
}
