import { NextFunction, Request, Response } from "express";
import { ApiError, errorEnvelope } from "../errors";
import { logger } from "../services/logger";

export interface EnvelopeSuccess<T> {
  data: T;
  request_id: string;
  timestamp: string;
}

export function successResponse<T>(req: Request, data: T): EnvelopeSuccess<T> {
  return {
    data,
    request_id: req.requestId,
    timestamp: new Date().toISOString()
  };
}

export function handleErrors(err: Error, req: Request, res: Response, _next: NextFunction) {
  if (err instanceof ApiError) {
    logger.warn("api_error", {
      request_id: req.requestId,
      trace_id: req.traceId,
      code: err.code,
      status_code: err.statusCode,
      message: err.message
    });
    res.status(err.statusCode).json(
      errorEnvelope(
        {
          ...err
        } as ApiError,
        req.requestId
      )
    );
    return;
  }

  logger.error("unhandled_error", {
    request_id: req.requestId,
    trace_id: req.traceId,
    error: err
  });
  res.status(500).json({
    code: "INTERNAL_ERROR",
    message: err.message || "Unexpected server error",
    request_id: req.requestId,
    timestamp: new Date().toISOString()
  });
}
