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

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

export const getPlayerReport = async (req: AuthenticatedRequest, res: Response) => {
  try {
    const roleId = req.roleId; // Ambil dari middleware jwt

    // Validasi roleId
    if (!roleId || isNaN(Number(roleId))) {
        return res.status(401).json({
          status: 'error',
          message: 'Unauthorized: roleId is required.',
          code: 401,
        });
      }

    // console.log('AuthenticatedRequestAuthenticatedRequest', req)
    const { id, nickname, page = '1', limit = '10' } = req.query;

    const errors: Record<string, string> = {};

    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 = {
        id: typeof id === 'string' && id.trim() !== '' ? id : undefined,
        nickname: typeof nickname === 'string' && nickname.trim() !== '' ? nickname : undefined,
        page: parseInt(page as string, 10),
        limit: parseInt(limit as string, 10),
        roleId: parseInt(roleId),
      };

    const { results, total } = await getPlayerGameReportsSvc(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,
    });
  }
};

