import { BaseEntity } from '@edr/api-common';
import { Column, Entity, Index, JoinColumn, ManyToOne } from 'typeorm';
import { ApprovalRule } from '../../rule-engine/entities/approval-rule.entity';
import { Booking } from './booking.entity';

export const APPROVAL_STEP_STATUSES = ['PENDING', 'APPROVED', 'REJECTED', 'SKIPPED'] as const;
export type ApprovalStepStatus = typeof APPROVAL_STEP_STATUSES[number];

@Entity({ schema: 'freight', name: 'booking_approval_step' })
@Index(['bookingId'])
@Index(['status'])
@Index(['bookingId', 'stepOrder'])
export class BookingApprovalStep extends BaseEntity {
  @Column({ name: 'booking_id', type: 'uuid' })
  bookingId!: string;

  @ManyToOne(() => Booking, (b) => b.approvalSteps, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'booking_id' })
  booking?: Booking;

  @Column({ name: 'approval_rule_id', type: 'uuid' })
  approvalRuleId!: string;

  @ManyToOne(() => ApprovalRule)
  @JoinColumn({ name: 'approval_rule_id' })
  approvalRule?: ApprovalRule;

  @Column({ name: 'step_order', type: 'smallint' })
  stepOrder!: number;

  @Column({ name: 'required_role', type: 'varchar', length: 30 })
  requiredRole!: string;

  @Column({ name: 'blocks_role', type: 'varchar', length: 30, nullable: true })
  blocksRole?: string | null;

  @Column({ name: 'status', type: 'varchar', length: 20, default: 'PENDING' })
  status!: ApprovalStepStatus;

  @Column({ name: 'actioned_by_staff_id', type: 'uuid', nullable: true })
  actionedByStaffId?: string | null;

  @Column({ name: 'actioned_at', type: 'timestamptz', nullable: true })
  actionedAt?: Date | null;

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