import {Op} from 'sequelize';
import GameLog from '../../db/models/AllGameTransaction';
import ReportTransactionDetail from '../../db/models/ReportTransactionDetail';

export const getAllGameTransactionsRepository = async (
  appId: string,
  page: number,
  limit: number,
  pagination: boolean,
  playerName?: string,
  filters?: {
    startTime?: Date;
    endTime?: Date;
    playerId?: string;
    gameTitle?: string;
  }
) => {
  try {
    const whereClause: any = {};

    // Search query
    if (playerName) {
      whereClause[Op.or] = [
        { player_nickname: { [Op.like]: `%${playerName}%` } }
      ];
    }

    // Filter by time
    if (filters?.startTime && filters?.endTime) {
      whereClause.transaction_date = {
        [Op.between]: [filters.startTime, filters.endTime],
      };
    } else if (filters?.startTime) {
      whereClause.transaction_date = {
        [Op.gte]: filters.startTime,
      };
    } else if (filters?.endTime) {
      whereClause.transaction_date = {
        [Op.lte]: filters.endTime,
      };
    }


    // Filter by partner_id
    if (filters?.playerId) {
      whereClause.client_player_id = filters.playerId;
    }

    // Filter by game_title
    if (filters?.gameTitle) {
      whereClause.game_title = { [Op.like]: `%${filters.gameTitle}%` };
    }

    if (appId) {
      whereClause.partner_id = appId;
    }


    if (pagination) {
      const offset = (page - 1) * limit;
      const { count, rows } = await ReportTransactionDetail.findAndCountAll({
        where: whereClause,
        offset,
        limit,
        subQuery: false,
        order: [['transaction_date', 'DESC']],
      });

      const totalPages = Math.ceil(count / limit);

      return {
        data: rows.map((row) => row.toJSON()),
        pagination: {
          totalRecords: count,
          totalPages,
          currentPage: page,
        },
      };
    } else {
      const { count, rows } = await GameLog.findAndCountAll({
        where: whereClause,
        order: [['create_date', 'DESC']],
      });

      return {
        data: rows.map((row) => row.toJSON()),
        totalRecords: count,
      };
    }
  } catch (error) {
    throw error;
  }
};


export const getGameTransactionByIdRepository = async (id: number) => {
  try {
    const result = await GameLog.findByPk(id);

    if (!result) {
      throw new Error(`Game transaction with id ${id} not found`);
    }

    return result.toJSON();
  } catch (error) {
    throw error;
  }
};
