import { FastifyReply } from "fastify";
import { ApiResponse, PaginationMeta } from "../types";

export function success<T>(
  reply: FastifyReply,
  data: T,
  statusCode = 200,
  message?: string,
): void {
  const response: ApiResponse<T> & { message?: string } = {
    success: true,
    data,
  };
  if (message) response.message = message;
  reply.status(statusCode).send(response);
}

export function paginated<T>(
  reply: FastifyReply,
  data: T,
  pagination: PaginationMeta,
): void {
  reply
    .status(200)
    .send({ success: true, data, pagination } satisfies ApiResponse<T>);
}

export function error(
  reply: FastifyReply,
  message: string,
  statusCode = 400,
): void {
  reply
    .status(statusCode)
    .send({ success: false, error: message } satisfies ApiResponse);
}

/** Parse and validate a numeric ID from route params. Returns NaN-safe number or sends 400 error. */
export function parseId(raw: string, reply: FastifyReply): number | null {
  const id = parseInt(raw, 10);
  if (isNaN(id) || id <= 0) {
    error(reply, "Neplatné ID", 400);
    return null;
  }
  return id;
}
