import { BaseEntity } from '@edr/api-common';
import { Column, Entity, Index, JoinColumn, ManyToOne } from 'typeorm';
import type { ContractDocumentChange } from '../contract-document-diff.util';
import { Contract } from './contract.entity';

/**
 * Append-only audit of contract document edits. The document stays editable
 * through the whole approval chain, so this records who changed which article
 * and when — the contract itself only ever holds the current snapshot.
 */
@Entity({ schema: 'freight', name: 'contract_document_revisions' })
@Index(['contractId'])
export class ContractDocumentRevision extends BaseEntity {
  @Column({ name: 'contract_id', type: 'uuid' })
  contractId!: string;

  @ManyToOne(() => Contract, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'contract_id' })
  contract?: Contract;

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

  /**
   * Who made the edit, captured at the time. Denormalised so the trail still
   * names them after a rename or a deactivated account.
   */
  @Column({ name: 'actor_name', type: 'varchar', length: 200, nullable: true })
  actorName?: string | null;

  /** The approval step's required role at the time of the edit. */
  @Column({ name: 'actor_role', type: 'varchar', length: 64, nullable: true })
  actorRole?: string | null;

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

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

  @Column({ name: 'changes', type: 'jsonb', default: () => `'[]'::jsonb` })
  changes!: ContractDocumentChange[];
}
