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

/**
 * Queue status type aligned with DDL fiscal.cfdi_stamp_queue.queue_status
 */
export type QueueStatus = 'pending' | 'processing' | 'completed' | 'failed';

/**
 * Stamp document type aligned with DDL fiscal.cfdi_stamp_queue.document_type
 */
export type StampDocumentType = 'invoice' | 'payment_complement';

/**
 * CFDI Stamp Queue Entity
 * Aligned with DDL: fiscal.cfdi_stamp_queue (28-cfdi-operations.sql)
 *
 * Asynchronous queue for CFDI stamping (timbrado). Documents are queued
 * for processing by a background worker that handles PAC communication.
 */
@Entity({ schema: 'fiscal', name: 'cfdi_stamp_queue' })
@Index('idx_cfdi_queue_tenant', ['tenantId'])
@Index('idx_cfdi_queue_status', ['queueStatus'])
@Index('idx_cfdi_queue_doc', ['documentType', 'documentId'])
export class CfdiStampQueue {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column({ type: 'uuid', nullable: false, name: 'tenant_id' })
  tenantId: string;

  // Document reference
  @Column({ type: 'varchar', length: 20, nullable: false, name: 'document_type' })
  documentType: StampDocumentType;

  @Column({ type: 'uuid', nullable: false, name: 'document_id' })
  documentId: string;

  // Priority (1=urgent, 5=normal, 10=low)
  @Column({ type: 'integer', default: 5, name: 'priority' })
  priority: number;

  // Queue status
  @Column({ type: 'varchar', length: 20, nullable: false, default: 'pending', name: 'queue_status' })
  queueStatus: QueueStatus;

  // Retry logic
  @Column({ type: 'integer', default: 0, name: 'attempts' })
  attempts: number;

  @Column({ type: 'integer', default: 3, name: 'max_attempts' })
  maxAttempts: number;

  @Column({ type: 'timestamptz', nullable: true, name: 'next_retry_at' })
  nextRetryAt: Date | null;

  // Result
  @Column({ type: 'timestamptz', nullable: true, name: 'completed_at' })
  completedAt: Date | null;

  @Column({ type: 'varchar', length: 36, nullable: true, name: 'result_cfdi_uuid' })
  resultCfdiUuid: string | null;

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

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

  @Column({ type: 'uuid', nullable: true, name: 'created_by' })
  createdBy: string | null;

  @UpdateDateColumn({ name: 'updated_at', type: 'timestamptz', nullable: true })
  updatedAt: Date | null;
}
