import sequelize from '../../db/config';
import {QueryTypes} from 'sequelize';

export const getPlayerGameReportsRpo = async ({
  appId,
  filters,
}: {
  appId: string;
  filters: {
    id?: string;
    nickname?: string;
    roleId: number;
    page: number;
    limit: number;
  };
}) => {
  try {
    console.log('appId', appId);
    console.log('roleIdrpo', filters.roleId);
    let whereClause = 'WHERE 1=1';
    const replacements: any = {};

    if (filters.id !== undefined) {
      whereClause += ' AND client_player_id = :id';
      replacements.id = filters.id;
    }

    if (filters.nickname !== undefined) {
      whereClause += ' AND nickname ILIKE :nickname';
      replacements.nickname = `%${filters.nickname}%`;
    }

    if (appId) {
      whereClause += ' AND platform_id = :appId';
      replacements.appId = appId;
    }

    const baseQuery = 'FROM pik_master."report_playerSummary"';

    const countQuery = `SELECT COUNT(*) AS total ${baseQuery} ${whereClause}`;
    const countResult: any = await sequelize.query(countQuery, {
      replacements,
      type: QueryTypes.SELECT,
    });
    const total = Number(countResult[0]?.total || 0);

    const offset = (filters.page - 1) * filters.limit;
    replacements.limit = filters.limit;
    replacements.offset = offset;

    const dataQuery = `
      SELECT * ${baseQuery}
      ${whereClause}
      ORDER BY create_date DESC
      LIMIT :limit OFFSET :offset
    `;

    const results = await sequelize.query(dataQuery, {
      replacements,
      type: QueryTypes.SELECT,
    });

    return {results, total};
  } catch (error) {
    console.error('getReplayGamesRpo error:', error);
    throw new Error('Failed to query player report data.');
  }
};
