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

@Entity('workflow_action')
@Index('idx_workflow_action_workflow_action_key', ['workflowConfiguration', 'actionKey'], { unique: true })
export class WorkflowAction {

  @PrimaryGeneratedColumn()
  id: number;

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

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

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

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

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

  @Column({ type: 'jsonb', nullable: true })
  permissions: string[] | null;

  @Column({ type: 'jsonb', nullable: true })
  endpoints: Record<string, unknown>[] | null;

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

  @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<WorkflowAction>) {
    Object.assign(this, partial);
  }
}
