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

export type SyncOperation = 'create' | 'update' | 'delete';
export type SyncStatus = 'pending' | 'processing' | 'completed' | 'failed' | 'conflict';
export type ConflictResolution = 'local_wins' | 'server_wins' | 'merged' | 'manual';

@Entity({ name: 'offline_sync_queue', schema: 'mobile' })
export class OfflineSyncQueue {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Index()
  @Column({ name: 'user_id', type: 'uuid' })
  userId: string;

  @Index()
  @Column({ name: 'device_id', type: 'uuid' })
  deviceId: string;

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

  @Column({ name: 'session_id', type: 'uuid', nullable: true })
  sessionId: string;

  // Operacion
  @Column({ name: 'entity_type', type: 'varchar', length: 50 })
  entityType: string; // sale, attendance, inventory_count, etc.

  @Column({ name: 'entity_id', type: 'uuid', nullable: true })
  entityId: string;

  @Column({ type: 'varchar', length: 20 })
  operation: SyncOperation;

  // Datos
  @Column({ type: 'jsonb' })
  payload: Record<string, any>;

  @Column({ type: 'jsonb', default: {} })
  metadata: Record<string, any>;

  // Orden y dependencias
  @Index()
  @Column({ name: 'sequence_number', type: 'bigint' })
  sequenceNumber: number;

  @Column({ name: 'depends_on', type: 'uuid', nullable: true })
  dependsOn: string;

  // Estado
  @Index()
  @Column({ type: 'varchar', length: 20, default: 'pending' })
  status: SyncStatus;

  // Procesamiento
  @Column({ name: 'retry_count', type: 'integer', default: 0 })
  retryCount: number;

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

  @Column({ name: 'last_error', type: 'text', nullable: true })
  lastError: string;

  @Column({ name: 'processed_at', type: 'timestamptz', nullable: true })
  processedAt: Date;

  // Conflicto
  @Column({ name: 'conflict_data', type: 'jsonb', nullable: true })
  conflictData: Record<string, any>;

  @Column({ name: 'conflict_resolved_at', type: 'timestamptz', nullable: true })
  conflictResolvedAt: Date;

  @Column({ name: 'conflict_resolution', type: 'varchar', length: 20, nullable: true })
  conflictResolution: ConflictResolution;

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

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