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

export type MobileSessionStatus = 'active' | 'paused' | 'expired' | 'terminated';

@Entity({ name: 'mobile_sessions', schema: 'mobile' })
export class MobileSession {
  @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;

  @Index()
  @Column({ name: 'branch_id', type: 'uuid', nullable: true })
  branchId: string;

  // Estado de la sesion
  @Index()
  @Column({ type: 'varchar', length: 20, default: 'active' })
  status: MobileSessionStatus;

  // Perfil activo
  @Column({ name: 'active_profile_id', type: 'uuid', nullable: true })
  activeProfileId: string;

  @Column({ name: 'active_profile_code', type: 'varchar', length: 10, nullable: true })
  activeProfileCode: string;

  // Modo de operacion
  @Column({ name: 'is_offline_mode', type: 'boolean', default: false })
  isOfflineMode: boolean;

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

  // Sincronizacion
  @Column({ name: 'last_sync_at', type: 'timestamptz', nullable: true })
  lastSyncAt: Date;

  @Column({ name: 'pending_sync_count', type: 'integer', default: 0 })
  pendingSyncCount: number;

  // Ubicacion
  @Column({ name: 'last_latitude', type: 'decimal', precision: 10, scale: 8, nullable: true })
  lastLatitude: number;

  @Column({ name: 'last_longitude', type: 'decimal', precision: 11, scale: 8, nullable: true })
  lastLongitude: number;

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

  // Metadata
  @Column({ name: 'app_version', type: 'varchar', length: 20, nullable: true })
  appVersion: string;

  @Column({ type: 'varchar', length: 20, nullable: true })
  platform: string; // ios, android

  @Column({ name: 'os_version', type: 'varchar', length: 20, nullable: true })
  osVersion: string;

  // Tiempos
  @Column({ name: 'started_at', type: 'timestamptz', default: () => 'CURRENT_TIMESTAMP' })
  startedAt: Date;

  @Column({ name: 'last_activity_at', type: 'timestamptz', default: () => 'CURRENT_TIMESTAMP' })
  lastActivityAt: Date;

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

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

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

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