import type { APIRoute } from 'astro';
import { requireApiToken } from '../../../lib/apiAuth';
import { publishPost } from '../../../lib/publisher';
import { downloadAndStoreImage } from '../../../lib/images';

export const POST: APIRoute = 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) : undefined,
      category: payload.category ? String(payload.category) : undefined,
      time: payload.time ? String(payload.time) : undefined,
      readTime: payload.readTime ? String(payload.readTime) : undefined,
      excerpt: payload.excerpt ? String(payload.excerpt) : undefined,
      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' },
    });
  }
};
