import {Request, Response} from 'express';
import * as Joi from 'joi';
import {
  getAllGameListsSvc,
  getGameListByIdSvc
} from './gameList.service';
import {responseJSON} from '../../helpers/response-handler';
import {CustomException} from '../../exceptions/CustomException';
import {EXCEPTION_MESSAGE} from '../../exceptions/EXCEPTION_MESSAGE';
import {gameListRes} from './gameList.dto';
import {isValidPositiveInt} from '../../../src/utils/validators'

export const index = async (req: Request, res: Response) => {
  try {
    const name = req.query.name as string | undefined;
    const pagination = req.query.p === 'true';
    const pageRaw = req.query.page;
    const limitRaw = req.query.limit;

    // Validasi manual jika pagination aktif
    if (pagination) {
      const errors: Record<string, string> = {};

      if (!isValidPositiveInt(pageRaw)) {
        errors.page = 'Page must be a positive number';
      }
      if (!isValidPositiveInt(limitRaw)) {
        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 page = parseInt(pageRaw as string, 10) || 1;
    const limit = parseInt(limitRaw as string, 10) || 5;

    const filters = { name, pagination, page, limit };

    const { rows, count } = await getAllGameListsSvc(filters);

    return responseJSON(req, res, {
      status: 'success',
      data: rows.map(gameListRes),
      pagination: pagination
        ? {
            page,
            limit,
            total: count,
            totalPages: Math.ceil(count / limit),
          }
        : undefined,
    });
  } catch (err: any) {
    console.error('GameList index error:', err);
    return responseJSON(req, res, {
      status: 'error',
      message: 'Failed to fetch game list.',
      detail: err.message,
    }, true);
  }
};


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

    const id = parseInt(req.params.id);
    console.log('idgamelist', id)
    if (isNaN(id) || id <= 0) {
      return res.status(400).json({
        status: 'error',
        message: 'Validation failed',
        errors: {
          id: 'ID must be a positive number',
        },
        code: 400,
      });
    }

    const data = await getGameListByIdSvc(id);

    if (!data) {
      return res.status(404).json({
        status: 'error',
        message: 'Game not found',
        code: 404,
      });
    }

    return responseJSON(req, res, {
      status: 'success',
      data,
    });
  } catch (error) {
    console.error('getGameListById error:', error);
    return res.status(500).json({
      status: 'error',
      message: 'Internal server error',
      detail: (error as Error).message,
    });
  }
};