import { InputParseError } from "../../entities/errors/common";
import {
  getPageBySlugInputSchema,
  type GetPageBySlugOutput,
  type IGetPageBySlugUseCase,
} from "../../application/use-cases/get-page-by-slug.use-case";

function presenter(value: GetPageBySlugOutput) {
  return value;
}

export type IGetPageBySlugController = ReturnType<typeof getPageBySlugController>;

export const getPageBySlugController =
  (getPageBySlugUseCase: IGetPageBySlugUseCase) =>
  async (input: unknown): Promise<ReturnType<typeof presenter> | undefined> => {
    const parsed = getPageBySlugInputSchema.safeParse(input);
    if (!parsed.success) {
      throw new InputParseError("Invalid get-page-by-slug input", { cause: parsed.error });
    }
    const result = await getPageBySlugUseCase(parsed.data);
    if (result === undefined) return undefined;
    return presenter(result);
  };
