import { Response } from 'express';
import { ApiResponse } from '../types/common.types';
import logger from './logger';

export class ResponseHandler {
  static success<T>(
    res: Response,
    data: T,
    message: string = 'Success',
    statusCode: number = 200,
    pagination?: {
      totalRecords: number;
      totalPages: number;
      currentPage: number;
      limit: number;
    }
  ): void {
    const response: ApiResponse<T> = {
      success: true,
      message,
      data,
      pagination,
      timestamp: new Date(),
    };

    res.status(statusCode).json(response);
  }

  static error(
    res: Response,
    message: string = 'Internal Server Error',
    statusCode: number = 500,
    error?: string
  ): void {
    const response: ApiResponse = {
      success: false,
      message,
      error,
      timestamp: new Date(),
    };

    logger.error(`Error response: ${message}`, { statusCode, error });
    res.status(statusCode).json(response);
  }

  static validationError(
    res: Response,
    message: string = 'Validation Error',
    errors?: any
  ): void {
    const response: ApiResponse = {
      success: false,
      message,
      error: errors,
      timestamp: new Date(),
    };

    logger.warn(`Validation error: ${message}`, { errors });
    res.status(400).json(response);
  }

  static notFound(
    res: Response,
    message: string = 'Resource not found'
  ): void {
    const response: ApiResponse = {
      success: false,
      message,
      timestamp: new Date(),
    };

    logger.warn(`Not found: ${message}`);
    res.status(404).json(response);
  }

  static unauthorized(
    res: Response,
    message: string = 'Unauthorized access'
  ): void {
    const response: ApiResponse = {
      success: false,
      message,
      timestamp: new Date(),
    };

    logger.warn(`Unauthorized: ${message}`);
    res.status(401).json(response);
  }

  static forbidden(
    res: Response,
    message: string = 'Forbidden access'
  ): void {
    const response: ApiResponse = {
      success: false,
      message,
      timestamp: new Date(),
    };

    logger.warn(`Forbidden: ${message}`);
    res.status(403).json(response);
  }
}
