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

@Entity({ name: 'usage_tracking', schema: 'billing' })
@Unique(['tenantId', 'periodStart'])
export class UsageTracking {
  @PrimaryGeneratedColumn('uuid')
  id: string;

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

  // Periodo
  @Index()
  @Column({ name: 'period_start', type: 'date' })
  periodStart: Date;

  @Column({ name: 'period_end', type: 'date' })
  periodEnd: Date;

  // Usuarios
  @Column({ name: 'active_users', type: 'integer', default: 0 })
  activeUsers: number;

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

  // Por perfil
  @Column({ name: 'users_by_profile', type: 'jsonb', default: {} })
  usersByProfile: Record<string, number>; // {"ADM": 2, "VNT": 5, "ALM": 3}

  // Por plataforma
  @Column({ name: 'users_by_platform', type: 'jsonb', default: {} })
  usersByPlatform: Record<string, number>; // {"web": 8, "mobile": 5, "desktop": 0}

  // Sucursales
  @Column({ name: 'active_branches', type: 'integer', default: 0 })
  activeBranches: number;

  // Storage
  @Column({ name: 'storage_used_gb', type: 'decimal', precision: 10, scale: 2, default: 0 })
  storageUsedGb: number;

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

  // API
  @Column({ name: 'api_calls', type: 'integer', default: 0 })
  apiCalls: number;

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

  // Transacciones
  @Column({ name: 'sales_count', type: 'integer', default: 0 })
  salesCount: number;

  @Column({ name: 'sales_amount', type: 'decimal', precision: 14, scale: 2, default: 0 })
  salesAmount: number;

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

  // Mobile
  @Column({ name: 'mobile_sessions', type: 'integer', default: 0 })
  mobileSessions: number;

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

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

  // Calculado
  @Column({ name: 'total_billable_amount', type: 'decimal', precision: 12, scale: 2, default: 0 })
  totalBillableAmount: number;

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

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