import type { NextFunction, Request, Response } from "express";

export class ApiError extends Error {
  public readonly code: string;
  public readonly status: number;
  public readonly details?: unknown;

  constructor(code: string, message: string, status = 400, details?: unknown) {
    super(message);
    this.code = code;
    this.status = status;
    this.details = details;
  }
}

export function ok<T>(res: Response, payload: T): Response<T> {
  return res.status(200).json(payload);
}

export function created<T>(res: Response, payload: T): Response<T> {
  return res.status(201).json(payload);
}

export function errorMiddleware(err: unknown, _req: Request, res: Response, _next: NextFunction): void {
  if (err instanceof ApiError) {
    res.status(err.status).json({
      ok: false,
      error: {
        code: err.code,
        message: err.message,
        details: err.details ?? null
      }
    });
    return;
  }

  const fallback = err instanceof Error ? err.message : "Unknown error";
  res.status(500).json({
    ok: false,
    error: {
      code: "INTERNAL_ERROR",
      message: fallback,
      details: null
    }
  });
}
