import { Article } from "../../models/Article";
import { requireAuth } from "../../utils/auth";

export default defineEventHandler(async (event) => {
  // Require authentication
  const user = await requireAuth(event);

  // Check if user can create articles
  if (!user.permissions.canEdit) {
    throw createError({
      statusCode: 403,
      statusMessage: "You do not have permission to create articles",
    });
  }

  // Get request body
  const body = await readBody(event);

  // Validate required fields
  if (!body.title || !body.slug || !body.content) {
    throw createError({
      statusCode: 400,
      statusMessage: "Title, slug, and content are required",
    });
  }

  // Check if slug already exists
  const existing = await Article.findOne({ slug: body.slug });
  if (existing) {
    throw createError({
      statusCode: 409,
      statusMessage: "An article with this slug already exists",
    });
  }

  // Create article
  try {
    const article = await Article.create({
      slug: body.slug,
      title: body.title,
      description: body.description || "",
      content: body.content,
      category: body.category || "general",
      tags: body.tags || [],
      accessLevel: body.accessLevel || "public",
      cohorts: body.cohorts || [],
      author: user.userId,
      status: body.status || "draft",
      publishedAt: body.status === "published" ? new Date() : null,
      revisions: [
        {
          content: body.content,
          author: user.userId,
          message: "Initial creation",
          createdAt: new Date(),
        },
      ],
    });

    return {
      success: true,
      slug: article.slug,
      message: "Article created successfully",
    };
  } catch (error) {
    console.error("Error creating article:", error);
    throw createError({
      statusCode: 500,
      statusMessage: "Failed to create article",
    });
  }
});
