import { z } from "zod";

const BLOG_CATEGORIES = [
  "Blogs-AI-Automation",
  "Blogs-Business-Growth",
  "Blogs-Custom-Software",
  "Blogs-Custom-Marketing",
  "Blogs-IT-Staff",
  "Blogs-Mobile-App",
  "Blogs-Social-Marketing",
  "Blogs-Web-Design",
];

const BlogCategoryEnum = z.enum(BLOG_CATEGORIES);
const BlogStatusEnum = z.enum(["Draft", "Published"]);

const ComponentSchema = z.object({
  _id: z.string().optional(),
  componentType: z.string().min(1, "Component type is required"),
  componentName: z.string().min(1, "Component name is required"),
  data: z.any(), // Flexible JSON data - can be any structure
  order: z.number().int().min(0).default(0),
  enabled: z.boolean().default(true),
});

const HeroSectionSchema = z.object({
  category: z.string().optional(),
  title: z.string().optional(),
  description: z.string().optional(),
});

const blogBase = z.object({
  category: BlogCategoryEnum,
  title: z.string().min(1, "Title is required").max(200, "Title is too long"),
  description: z.string().optional(),
  heroSection: HeroSectionSchema.optional(),
  components: z.array(ComponentSchema).default([]),
  status: BlogStatusEnum.default("Draft"),
});

const createBlogSchema = blogBase;
const updateBlogSchema = blogBase.partial();

function normalizeBlogPayload(payload) {
  if (!payload || typeof payload !== "object") {
    return {};
  }

  const normalized = { ...payload };

  // Ensure components is an array
  if (!Array.isArray(normalized.components)) {
    normalized.components = [];
  }

  // Sort components by order and preserve _id if it exists
  normalized.components = normalized.components
    .map((component, index) => {
      const normalizedComponent = {
        componentType: component.componentType || "",
        componentName: component.componentName || component.componentType || `Component ${index + 1}`,
        data: component.data || {},
        order: typeof component.order === "number" ? component.order : index,
        enabled: typeof component.enabled === "boolean" ? component.enabled : true,
      };
      // Preserve _id if it exists (for existing components)
      if (component._id) {
        normalizedComponent._id = component._id;
      }
      return normalizedComponent;
    })
    .sort((a, b) => a.order - b.order);

  return normalized;
}

export {
  BLOG_CATEGORIES,
  BlogCategoryEnum,
  BlogStatusEnum,
  ComponentSchema,
  HeroSectionSchema,
  createBlogSchema,
  updateBlogSchema,
  normalizeBlogPayload,
};

