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

export type EventCategory = 'user' | 'api' | 'storage' | 'transaction' | 'mobile';

/**
 * Entidad para eventos de uso en tiempo real.
 * Utilizada para calculo de billing y tracking granular.
 * Mapea a billing.usage_events (DDL: 05-billing-usage.sql)
 */
@Entity({ name: 'usage_events', schema: 'billing' })
export class UsageEvent {
  @PrimaryGeneratedColumn('uuid')
  id: string;

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

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

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

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

  // Evento
  @Index()
  @Column({ name: 'event_type', type: 'varchar', length: 50 })
  eventType: string; // login, api_call, document_upload, sale, invoice, sync

  @Index()
  @Column({ name: 'event_category', type: 'varchar', length: 30 })
  eventCategory: EventCategory;

  // Detalles
  @Column({ name: 'profile_code', type: 'varchar', length: 10, nullable: true })
  profileCode: string;

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

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

  @Column({ name: 'resource_type', type: 'varchar', length: 50, nullable: true })
  resourceType: string;

  // Metricas
  @Column({ type: 'integer', default: 1 })
  quantity: number;

  @Column({ name: 'bytes_used', type: 'bigint', default: 0 })
  bytesUsed: number;

  @Column({ name: 'duration_ms', type: 'integer', nullable: true })
  durationMs: number;

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

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