import {Request, Response} from 'express';
import {responseJSON} from '../../helpers/response-handler';
import {
  getAllGameTransactionsService,
  getGameTransactionByIdService,
} from './allGameTransaction.service';
import {gameTransactionRes} from './allGameTransaction.dto';

export interface AuthenticatedRequest extends Request {
  user?: any;
  id?: string;
  roleId?: number;
}

/**
 * GET /all-game-transactions
 * Query params:
 * - p: page number (default 1)
 * - l: limit (default 10)
 * - pg: pagination toggle (true/false)
 * - search: optional keyword to search by name, gametype, or app_id
 */

export const index = async (req: AuthenticatedRequest, res: Response) => {
  try {
    const { roleId } = req;

    const {
      page = '1',
      pg,
      l,
      limit: limitQuery,
      player_name,
      start_time,
      end_time,
      player_id,
      game_title,
    } = req.query;

    const currentPage = parseInt(page as string, 10);
    const limit = parseInt((limitQuery || l || '10') as string, 10);
    const usePagination = pg === 'true' || pg === '1';

    const filters = {
      playerName: player_name?.toString(),
      startTime: start_time ? new Date(start_time.toString()) : undefined,
      endTime: end_time ? new Date(end_time.toString()) : undefined,
      playerId: player_id?.toString(),
      gameTitle: game_title?.toString(),
    };

    const result = await getAllGameTransactionsService(
      currentPage,
      limit,
      usePagination,
      roleId,
      filters.playerName,
      filters,
    );

    const data = result.data.map(gameTransactionRes);

    let paginationInfo;
    if (usePagination && result.pagination) {
      const { totalRecords, totalPages, currentPage } = result.pagination;

      paginationInfo = {
        page: currentPage,
        limit,
        total: totalRecords,
        totalPages,
        prevPage: currentPage > 1 ? currentPage - 1 : null,
        nextPage: currentPage < totalPages ? currentPage + 1 : null,
      };
    }

    return responseJSON(req, res, {
      data,
      ...(paginationInfo && { pagination: paginationInfo }),
    });
  } catch (error: any) {
    return responseJSON(req, res, { message: error.message }, true);
  }
};



// export const index = async (req: AuthenticatedRequest, res: Response) => {
//   try {
//     const roleId = req.roleId; // Ambil dari middleware jwt
//     console.log('roleIdkamu', roleId);

//     const page = parseInt(req.query.page as string, 10) || 1;
//     const limit = parseInt(req.query.size as string, 10) || 10;
//     const pagination = req.query.pg === 'true' || req.query.pg === '1';

//     const playerName = req.query.player_name
//       ? String(req.query.player_name)
//       : undefined;
//     const startTime = req.query.start_time
//       ? new Date(String(req.query.start_time))
//       : undefined;
//     const endTime = req.query.end_time
//       ? new Date(String(req.query.end_time))
//       : undefined;
//     const playerId = req.query.player_id
//       ? String(req.query.player_id)
//       : undefined;
//     const gameTitle = req.query.game_title
//       ? String(req.query.game_title)
//       : undefined;

//     console.log('playerName', playerName);

//     const result = await getAllGameTransactionsService(
//       page,
//       limit,
//       pagination,
//       roleId,
//       playerName,
//       {startTime, endTime, playerId, gameTitle},
//     );

//     const transformedData = result.data.map(gameTransactionRes);

//     // const dataPagination = {
//     //   page: filters.page,
//     //   limit: filters.limit,
//     //   total,
//     //   totalPages,
//     //   prevPage: filters.page > 1 ? filters.page - 1 : null,
//     //   nextPage: filters.page < totalPages ? filters.page + 1 : null,
//     // };
//     return responseJSON(req, res, {
//       data: transformedData,
//       ...(result.pagination && {pagination: result.pagination}),
//     });
//   } catch (error: any) {
//     return responseJSON(req, res, {message: error.message}, true);
//   }
// };

/**
 * GET /all-game-transactions/:id
 */
export const show = async (req: Request, res: Response) => {
  try {
    const {id} = req.params;

    const result = await getGameTransactionByIdService(Number(id));

    return responseJSON(req, res, {data: result});
  } catch (error: any) {
    return responseJSON(req, res, {message: error.message}, true);
  }
};
