import {
  Column,
  CreateDateColumn,
  DeleteDateColumn,
  Entity,
  Index,
  JoinColumn,
  ManyToOne,
  PrimaryGeneratedColumn,
  UpdateDateColumn,
} from 'typeorm';
import { User } from './user.entity';
import { WorkflowConfiguration } from './workflow-configuration.entity';
import { WorkflowVariableMaster } from './workflow-variable-master.entity';

/**
 * Junction table linking workflow configurations to variables
 * Defines which variables are used by each workflow
 */
@Entity('workflow_configuration_variable')
@Index('idx_wf_config_variable_workflow', ['workflowConfigId'])
@Index('idx_wf_config_variable_variable', ['variableMasterId'])
export class WorkflowConfigurationVariable {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ name: 'workflow_config_id', type: 'int' })
  workflowConfigId: number;

  @ManyToOne(() => WorkflowConfiguration, wf => wf.variables, { nullable: false })
  @JoinColumn({ name: 'workflow_config_id' })
  workflowConfiguration: WorkflowConfiguration;

  @Column({ name: 'variable_master_id', type: 'int' })
  variableMasterId: number;

  @ManyToOne(() => WorkflowVariableMaster, vm => vm.workflowConfigurations, { nullable: false })
  @JoinColumn({ name: 'variable_master_id' })
  variableMaster: WorkflowVariableMaster;

  @Column({ name: 'is_required', type: 'boolean', default: false })
  isRequired: boolean; // Whether this variable is mandatory for this workflow

  @Column({ name: 'variable_order', type: 'int', nullable: true })
  variableOrder: number | null; // Order in which to fetch/display

  @Column({ name: 'override_alias', type: 'varchar', length: 100, nullable: true })
  overrideAlias: string | null; // Override the default alias for this workflow

  @Column({ name: 'override_default_value', type: 'text', nullable: true })
  overrideDefaultValue: string | null; // Override default value for this workflow

  @Column({ type: 'jsonb', nullable: true })
  metadata: Record<string, unknown> | null; // Workflow-specific configuration

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

  @UpdateDateColumn({ name: 'updated_at', type: 'timestamptz', default: () => 'CURRENT_TIMESTAMP', onUpdate: 'CURRENT_TIMESTAMP' })
  updatedAt: Date;

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

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

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

  @ManyToOne(() => User, { nullable: true })
  @JoinColumn({ name: 'created_by' })
  createdBy: User | null;

  @ManyToOne(() => User, { nullable: true })
  @JoinColumn({ name: 'updated_by' })
  updatedBy: User | null;

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