import { Request, Response, NextFunction } from 'express'
import type { ApiResponse } from '../types/index.js'

export function errorHandler(err: Error, req: Request, res: Response, next: NextFunction) {
  console.error('Error:', err.message)
  const response: ApiResponse = {
    success: false,
    data: null,
    error: err.message || 'Internal server error',
  }
  res.status(500).json(response)
}

export function notFoundHandler(req: Request, res: Response) {
  const response: ApiResponse = {
    success: false,
    data: null,
    error: `Route not found: ${req.method} ${req.path}`,
  }
  res.status(404).json(response)
}

export function sendSuccess<T>(res: Response, data: T, meta?: any) {
  const response: ApiResponse<T> = { success: true, data, meta }
  res.json(response)
}

export function sendError(res: Response, error: string, status = 400) {
  const response: ApiResponse = { success: false, data: null, error }
  res.status(status).json(response)
}

export function parseMonth(req: Request): string {
  const month = (req.query.month as string) || '2026-04'
  return month.length === 7 ? `${month}-01` : month
}

export function parsePagination(req: Request) {
  const page = parseInt((req.query.page as string) || '1')
  const pageSize = parseInt((req.query.page_size as string) || '50')
  const offset = (page - 1) * pageSize
  return { page, pageSize, offset }
}
