/**
 * SyncConflict Entity
 * Offline synchronization conflict tracking and resolution
 * Compatible with erp-core sync-conflict.entity
 *
 * @module Mobile
 */

import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  Index,
  ManyToOne,
  JoinColumn,
} from 'typeorm';
import { OfflineSyncQueue } from './offline-sync-queue.entity';

export type ConflictType = 'data_conflict' | 'version_conflict' | 'delete_conflict' | 'constraint_conflict';
export type ConflictResolutionType = 'local_wins' | 'server_wins' | 'merged' | 'manual';

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

  @Index()
  @Column({ name: 'sync_queue_id', type: 'uuid' })
  syncQueueId: string;

  @ManyToOne(() => OfflineSyncQueue, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'sync_queue_id' })
  syncQueue: OfflineSyncQueue;

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

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

  @Column({ name: 'conflict_type', type: 'varchar', length: 30 })
  conflictType: ConflictType;

  @Column({ name: 'local_data', type: 'jsonb' })
  localData: Record<string, any>;

  @Column({ name: 'server_data', type: 'jsonb' })
  serverData: Record<string, any>;

  @Column({ type: 'varchar', length: 20, nullable: true })
  resolution: ConflictResolutionType;

  @Column({ name: 'merged_data', type: 'jsonb', nullable: true })
  mergedData: Record<string, any>;

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

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

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