import { BaseEntity } from '@edr/api-common';
import { Column, Entity, Index, JoinColumn, ManyToOne } from 'typeorm';

import { PriorityConfig } from './priority-config.entity';

export type PriorityRuleChangeAction = 'CREATE' | 'UPDATE' | 'DELETE';
export type PriorityRuleChangeStatus = 'PENDING' | 'APPROVED' | 'REJECTED';

/**
 * One proposed change to a priority rule, awaiting approval. Every
 * create/update/delete of a priority config is filed here first; an approver
 * applies (which runs the real mutation, including range-collision checks) or
 * rejects it. `payload` holds the proposed field values (null for DELETE);
 * `priorityConfigId` the target rule (null for CREATE).
 */
@Entity({ schema: 'freight', name: 'priority_rule_change_requests' })
@Index(['status'])
export class PriorityRuleChangeRequest extends BaseEntity {
  @Column({ name: 'action', type: 'varchar', length: 10 })
  action!: PriorityRuleChangeAction;

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

  @ManyToOne(() => PriorityConfig, { nullable: true })
  @JoinColumn({ name: 'priority_config_id' })
  priorityConfig?: PriorityConfig | null;

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

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

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

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

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

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