import {
  Entity,
  Column,
  PrimaryGeneratedColumn,
  CreateDateColumn,
  UpdateDateColumn,
  Index,
} from 'typeorm';

/**
 * GDPR deletion request status
 */
export enum DeletionStatus {
  /** Deletion request received and queued */
  PENDING = 'PENDING',
  /** Deletion job is currently processing */
  PROCESSING = 'PROCESSING',
  /** Deletion completed successfully */
  COMPLETED = 'COMPLETED',
  /** Deletion failed with errors */
  FAILED = 'FAILED',
  /** Deletion partially completed (some tables failed) */
  PARTIAL = 'PARTIAL',
}

/**
 * Per-table deletion result tracking
 */
export interface TableDeletionResult {
  table: string;
  status: 'success' | 'failed' | 'skipped';
  recordsDeleted?: number;
  recordsAnonymized?: number;
  error?: string;
  startedAt: string;
  completedAt: string;
  durationMs: number;
}

/**
 * DeletionAuditLog - GDPR Article 17 compliance tracking
 *
 * Records all user data deletion requests and their execution status.
 * Provides full audit trail for GDPR compliance verification.
 *
 * GDPR Requirements:
 * - Article 17: Right to erasure ("right to be forgotten")
 * - Article 30: Records of processing activities
 * - Recital 82: Demonstrable compliance
 *
 * Tax Compliance:
 * - Revenue data is ANONYMIZED (userId set to NULL) not deleted
 * - Aggregate statistics preserved for financial records
 * - Individual revenue amounts retained for tax audit requirements
 */
@Entity('deletion_audit_logs')
export class DeletionAuditLog {
  @PrimaryGeneratedColumn('uuid')
  id!: string;

  @Column('uuid', { name: 'subject_id' })
  @Index()
  subjectId!: string;

  @Column({
    type: 'enum',
    enum: DeletionStatus,
    default: DeletionStatus.PENDING,
  })
  @Index()
  status!: DeletionStatus;

  @Column('timestamp', { name: 'requested_at', default: () => 'CURRENT_TIMESTAMP' })
  @Index()
  requestedAt!: Date;

  @Column('timestamp', { name: 'started_at', nullable: true })
  startedAt?: Date;

  @Column('timestamp', { name: 'completed_at', nullable: true })
  @Index()
  completedAt?: Date;

  @Column('int', { name: 'duration_ms', nullable: true })
  durationMs?: number;

  /**
   * Per-table deletion results with detailed status
   */
  @Column('jsonb', { name: 'table_results', default: [] })
  tableResults!: TableDeletionResult[];

  /**
   * Summary counts for quick verification
   */
  @Column('int', { name: 'total_records_deleted', default: 0 })
  totalRecordsDeleted!: number;

  @Column('int', { name: 'total_records_anonymized', default: 0 })
  totalRecordsAnonymized!: number;

  /**
   * Queue job ID for correlation with job system
   */
  @Column('varchar', { length: 100, name: 'job_id', nullable: true })
  @Index()
  jobId?: string;

  /**
   * Error details if deletion failed
   */
  @Column('jsonb', { name: 'error_details', nullable: true })
  errorDetails?: {
    message: string;
    stack?: string;
    failedTables?: string[];
    partialResults?: TableDeletionResult[];
  };

  /**
   * Verification status - confirms no user data remains
   */
  @Column('boolean', { name: 'verified', default: false })
  @Index()
  verified!: boolean;

  @Column('timestamp', { name: 'verified_at', nullable: true })
  verifiedAt?: Date;

  /**
   * Count of records found during verification (should be 0)
   */
  @Column('int', { name: 'verification_records_found', nullable: true })
  verificationRecordsFound?: number;

  /**
   * Additional metadata for audit purposes
   */
  @Column('jsonb', { nullable: true })
  metadata?: {
    requestSource?: 'user' | 'admin' | 'automated';
    requestedBy?: string;
    retryCount?: number;
    gdprArticle?: string;
    notes?: string;
  };

  @CreateDateColumn({ name: 'created_at', type: 'timestamptz' })
  createdAt!: Date;

  @UpdateDateColumn({ name: 'updated_at', type: 'timestamptz' })
  updatedAt!: Date;
}
