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 interface DateRange {
  start: string
  end: string
  mode: 'month' | 'quarter' | 'halfyear' | 'year' | 'custom'
  label: string
}

export function parseDateRange(req: Request): DateRange {
  const mode = ((req.query.range_mode as string) || 'month') as 'month' | 'quarter' | 'halfyear' | 'year' | 'custom'
  const month = parseMonth(req)
  const startDate = new Date(month)

  const addMonths = (d: Date, n: number): string => {
    const r = new Date(d)
    r.setMonth(r.getMonth() + n)
    return r.toISOString().slice(0, 10)
  }

  switch (mode) {
    case 'quarter':
      return { start: month, end: addMonths(startDate, 3), mode, label: '季度' }
    case 'halfyear':
      return { start: month, end: addMonths(startDate, 6), mode, label: '半年' }
    case 'year':
      return { start: month, end: addMonths(startDate, 12), mode, label: '全年' }
    case 'custom': {
      const start = (req.query.start_date as string) || month
      const end = (req.query.end_date as string) || addMonths(new Date(start), 1)
      return { start, end, mode, label: '自定义' }
    }
    default:
      return { start: month, end: addMonths(startDate, 1), mode, label: '月度' }
  }
}

export function prevYearMonth(month: string): string {
  const d = new Date(month)
  d.setFullYear(d.getFullYear() - 1)
  return d.toISOString().slice(0, 10)
}

export function prevMonth(month: string): string {
  const d = new Date(month)
  d.setMonth(d.getMonth() - 1)
  return d.toISOString().slice(0, 10)
}

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 }
}
