// src/models/usage-log.model.js
// 사용량 로그 모델

const { DataTypes, Op } = require('sequelize');

module.exports = (sequelize) => {
  const UsageLog = sequelize.define('UsageLog', {
    id: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      primaryKey: true,
    },
    userId: {
      type: DataTypes.UUID,
      allowNull: false,
      references: {
        model: 'users',
        key: 'id',
      },
      comment: '사용자 ID',
    },
    apiKeyId: {
      type: DataTypes.UUID,
      allowNull: true,
      references: {
        model: 'api_keys',
        key: 'id',
      },
      comment: 'API 키 ID',
    },
    providerId: {
      type: DataTypes.UUID,
      allowNull: true,
      references: {
        model: 'llm_providers',
        key: 'id',
      },
      comment: 'LLM 프로바이더 ID',
    },
    providerName: {
      type: DataTypes.STRING(50),
      allowNull: true,
      comment: 'LLM 프로바이더 이름',
    },
    modelName: {
      type: DataTypes.STRING(100),
      allowNull: true,
      comment: '사용된 모델 이름',
    },
    promptTokens: {
      type: DataTypes.INTEGER,
      defaultValue: 0,
      comment: '프롬프트 토큰 수',
    },
    completionTokens: {
      type: DataTypes.INTEGER,
      defaultValue: 0,
      comment: '완성 토큰 수',
    },
    totalTokens: {
      type: DataTypes.INTEGER,
      defaultValue: 0,
      comment: '총 토큰 수',
    },
    costUsd: {
      type: DataTypes.DECIMAL(10, 6),
      defaultValue: 0,
      comment: '비용 (USD)',
    },
    responseTimeMs: {
      type: DataTypes.INTEGER,
      allowNull: true,
      comment: '응답 시간 (밀리초)',
    },
    success: {
      type: DataTypes.BOOLEAN,
      defaultValue: true,
      comment: '성공 여부',
    },
    errorMessage: {
      type: DataTypes.TEXT,
      allowNull: true,
      comment: '에러 메시지',
    },
    requestIp: {
      type: DataTypes.STRING(45),
      allowNull: true,
      comment: '요청 IP 주소',
    },
    userAgent: {
      type: DataTypes.STRING(500),
      allowNull: true,
      comment: 'User-Agent',
    },
  }, {
    tableName: 'usage_logs',
    timestamps: true,
    underscored: true,
    indexes: [
      {
        fields: ['user_id'],
      },
      {
        fields: ['api_key_id'],
      },
      {
        fields: ['created_at'],
      },
      {
        fields: ['provider_name'],
      },
    ],
  });

  // 클래스 메서드: 사용자별 일별 사용량 조회
  UsageLog.getDailyUsageByUser = async function(userId, startDate, endDate) {
    return this.findAll({
      where: {
        userId,
        createdAt: {
          [Op.between]: [startDate, endDate],
        },
      },
      attributes: [
        [sequelize.fn('DATE', sequelize.col('created_at')), 'date'],
        [sequelize.fn('SUM', sequelize.col('total_tokens')), 'totalTokens'],
        [sequelize.fn('SUM', sequelize.col('cost_usd')), 'totalCost'],
        [sequelize.fn('COUNT', sequelize.col('id')), 'requestCount'],
      ],
      group: [sequelize.fn('DATE', sequelize.col('created_at'))],
      order: [[sequelize.fn('DATE', sequelize.col('created_at')), 'ASC']],
      raw: true,
    });
  };

  // 클래스 메서드: 사용자별 월간 총 사용량 조회
  UsageLog.getMonthlyTotalByUser = async function(userId, year, month) {
    const startDate = new Date(year, month - 1, 1);
    const endDate = new Date(year, month, 0, 23, 59, 59);

    const result = await this.findOne({
      where: {
        userId,
        createdAt: {
          [Op.between]: [startDate, endDate],
        },
      },
      attributes: [
        [sequelize.fn('SUM', sequelize.col('total_tokens')), 'totalTokens'],
        [sequelize.fn('SUM', sequelize.col('cost_usd')), 'totalCost'],
        [sequelize.fn('COUNT', sequelize.col('id')), 'requestCount'],
      ],
      raw: true,
    });

    return {
      totalTokens: parseInt(result.totalTokens, 10) || 0,
      totalCost: parseFloat(result.totalCost) || 0,
      requestCount: parseInt(result.requestCount, 10) || 0,
    };
  };

  return UsageLog;
};
