import { r as requireApiToken } from '../../../chunks/apiAuth_DcNSM7D5.mjs';
import { p as publishPost } from '../../../chunks/publisher_Dj_UvF8J.mjs';
import { d as downloadAndStoreImage } from '../../../chunks/images_DSuHPXn1.mjs';
export { renderers } from '../../../renderers.mjs';

const POST = async (context) => {
  const unauthorized = requireApiToken(context);
  if (unauthorized) {
    return unauthorized;
  }
  try {
    const payload = await context.request.json();
    let image = payload.image;
    let thumbnail = payload.thumbnail;
    if (payload.imageUrl && !image) {
      const storedImage = await downloadAndStoreImage(String(payload.imageUrl));
      image = storedImage?.image;
      thumbnail = storedImage?.thumbnail;
    }
    const post = await publishPost({
      title: String(payload.title ?? ""),
      slug: payload.slug ? String(payload.slug) : void 0,
      category: payload.category ? String(payload.category) : void 0,
      time: payload.time ? String(payload.time) : void 0,
      readTime: payload.readTime ? String(payload.readTime) : void 0,
      excerpt: payload.excerpt ? String(payload.excerpt) : void 0,
      body: Array.isArray(payload.body) ? payload.body.map(String) : String(payload.body ?? ""),
      status: payload.status === "approved" ? "approved" : "pending",
      image,
      thumbnail
    });
    return new Response(JSON.stringify({ ok: true, post }), {
      headers: { "content-type": "application/json; charset=utf-8" }
    });
  } catch (error) {
    return new Response(JSON.stringify({ ok: false, error: error instanceof Error ? error.message : "Invalid request" }), {
      status: 400,
      headers: { "content-type": "application/json; charset=utf-8" }
    });
  }
};

const _page = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
  __proto__: null,
  POST
}, Symbol.toStringTag, { value: 'Module' }));

const page = () => _page;

export { page };
