import type { ErrorRequestHandler } from "express";
import { ZodError } from "zod";

import { AppError } from "../utils/app-error.js";

type PgError = Error & {
  code?: string;
  constraint?: string;
  detail?: string;
};

export const errorHandler: ErrorRequestHandler = (error, _request, response, _next) => {
  if (error instanceof AppError) {
    return response.status(error.statusCode).json({
      error: error.message,
      details: error.details
    });
  }

  if (error instanceof ZodError) {
    return response.status(400).json({
      error: "Validation failed",
      details: error.flatten()
    });
  }

  const pgError = error as PgError;

  if (pgError.code === "23P01") {
    return response.status(409).json({
      error: "Booking conflict detected",
      details: pgError.detail
    });
  }

  if (pgError.code === "23505") {
    return response.status(409).json({
      error: "Unique value conflict",
      details: pgError.detail ?? pgError.constraint
    });
  }

  console.error(error);

  return response.status(500).json({
    error: "Internal server error"
  });
};
