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

/**
 * Token 使用统计实体
 * 记录每次 Claude API 调用的 token 消耗
 */
@Entity('token_usages')
@Index('idx_token_usages_user', ['userId'])
@Index('idx_token_usages_conversation', ['conversationId'])
@Index('idx_token_usages_created', ['createdAt'])
@Index('idx_token_usages_model', ['model'])
export class TokenUsageEntity {
  @PrimaryGeneratedColumn('uuid')
  id: string;

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

  @Column({ name: 'conversation_id', type: 'uuid' })
  conversationId: string;

  @Column({ name: 'message_id', type: 'uuid', nullable: true })
  messageId: string | null;

  @Column({ length: 50 })
  model: string;

  // 输入 tokens
  @Column({ name: 'input_tokens', default: 0 })
  inputTokens: number;

  // 输出 tokens
  @Column({ name: 'output_tokens', default: 0 })
  outputTokens: number;

  // 缓存创建的 tokens (Prompt Caching)
  @Column({ name: 'cache_creation_tokens', default: 0 })
  cacheCreationTokens: number;

  // 缓存命中的 tokens (Prompt Caching)
  @Column({ name: 'cache_read_tokens', default: 0 })
  cacheReadTokens: number;

  // 总 tokens (input + output)
  @Column({ name: 'total_tokens', default: 0 })
  totalTokens: number;

  // 估算成本 (美元)
  @Column({ name: 'estimated_cost', type: 'decimal', precision: 10, scale: 6, default: 0 })
  estimatedCost: number;

  // 意图类型
  @Column({ name: 'intent_type', type: 'varchar', length: 30, nullable: true })
  intentType: string | null;

  // 工具调用次数
  @Column({ name: 'tool_calls', default: 0 })
  toolCalls: number;

  // 响应长度(字符数)
  @Column({ name: 'response_length', default: 0 })
  responseLength: number;

  // 请求耗时(毫秒)
  @Column({ name: 'latency_ms', default: 0 })
  latencyMs: number;

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