import * as Sentry from "@sentry/node";
import type { Context } from "hono";
import { HTTPException } from "hono/http-exception";
import type { ContentfulStatusCode } from "hono/utils/http-status";

// const isDev = process.env.NODE_ENV !== "production";

export const success = <T>(
  c: Context,
  data: T,
  message = "Success",
  status?: ContentfulStatusCode | undefined,
) => {
  return c.json(
    {
      success: true,
      message,
      data,
    },
    status ?? 200,
  );
};

export function getErrorMessage(err: unknown, fallback?: string): string {
  if (err instanceof HTTPException)
return err.message;
  if (err instanceof Error)
return err.message;

  if (
    typeof err === "object" &&
    err !== null &&
    "detail" in err &&
    typeof (err as any).detail === "string"
  ) {
    return (err as any).detail;
  }

  return fallback ?? "Server error occured";
}

export const error = (
  c: Context,
  message?: string,
  status?: ContentfulStatusCode | undefined,
  errorDetail?: unknown,
) => {
  const errorMessage = getErrorMessage(errorDetail, message);
  const body: Record<string, unknown> = {
    success: false,
    message: errorMessage,
    data: null,
  };
  const email = c.get("email");
  if (email) {
    Sentry.setUser({
      email,
    });
    Sentry.captureException(errorMessage);
  }
  if (errorDetail) {
    body.error = errorDetail;
  }

  return c.json(body, status ?? 400);
};
