import {Request, Response} from 'express';
import * as Joi from 'joi';
import {
  getReplayGamesSvc,
} from './replayRecord.service';
import {responseJSON} from '../../helpers/response-handler';
import {CustomException} from '../../exceptions/CustomException';
import {EXCEPTION_MESSAGE} from '../../exceptions/EXCEPTION_MESSAGE';
import {isValidPositiveInt} from '../../utils/validators';

declare namespace Express {
  export interface Request {
    user?: any; // atau custom type kamu
  }
}

export const replayReport = async (req: Request, res: Response) => {
  try {

    const {roundId, gameId, page = '1', limit = '10'} = req.query;

    // errors digunakan untuk menyimpan semua pesan kesalahan dari validasi field tertentu
    const errors: Record<string, string> = {};

    // Validasi page & limit
    if (!isValidPositiveInt(page)) {
      errors.page = 'Page must be a positive number';
    }

    if (!isValidPositiveInt(limit)) {
      errors.limit = 'Limit must be a positive number';
    }

    if (Object.keys(errors).length > 0) {
      return res.status(400).json({
        status: 'error',
        message: 'Validation failed',
        errors,
        code: 400,
      });
    }

    const filters = {
      roundId: roundId as string | undefined,
      gameId: gameId ? parseInt(gameId as string, 10) : undefined,
      page: parseInt(page as string, 10),
      limit: parseInt(limit as string, 10),
    };

    const {results, total} = await getReplayGamesSvc(filters);

    const totalPages = Math.ceil(total / filters.limit);
    const pagination = {
      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, {
      status: 'success',
      data_count: results.length,
      data: results,
      pagination,
    });
  } catch (error) {
    console.error('ReplayGameController error:', error);
    return res.status(500).json({
      status: 'error',
      message: 'Internal server error',
      detail: (error as Error).message,
    });
  }
};
