import { Injectable, Logger } from '@nestjs/common';
import { PrismaService } from '../../../infrastructure/database/prisma.service';

export interface UsageLogEntry {
  userId: string;
  feature: string;
  provider: string;
  model: string;
  tier: string;
  promptKey: string;
  promptVersion: string;
  inputTokens: number;
  outputTokens: number;
  estimatedCost: number;
  latencyMs: number;
  success: boolean;
  errorMessage?: string;
}

@Injectable()
export class AiUsageLogService {
  private readonly logger = new Logger(AiUsageLogService.name);

  constructor(private readonly prisma: PrismaService) {}

  async log(entry: UsageLogEntry): Promise<void> {
    try {
      await this.prisma.aiUsageLog.create({ data: entry });
    } catch (error) {
      this.logger.error(`Failed to write AI usage log: ${(error as Error).message}`);
    }
  }
}
