import formatSlug from "@/utils/payload/formatSlug";
import setAuthor from "@/utils/payload/setAuthor";
import { lexicalEditor } from "@payloadcms/richtext-lexical";
import type { CollectionConfig } from "payload";

export const Blogs: CollectionConfig = {
  slug: "blogs",
  labels: { plural: "Posts", singular: "Post" },
  versions: {
    drafts: {
      validate: true,
    },
  },
  fields: [
    {
      name: "title",
      type: "text",
      required: true,
    },
    {
      name: "slug",
      type: "text",
      hooks: {
        beforeValidate: [formatSlug("title")],
      },
    },
    {
      name: "img",
      label: "Image",
      type: "upload",
      relationTo: "media",
      required: true,
    },
    {
      name: "content",
      type: "richText",
      required: true,
      editor: lexicalEditor({}),
    },
    {
      name: "categories",
      type: "relationship",
      relationTo: "blogCategories",
      hasMany: true,
    },
    {
      name: "tags",
      type: "relationship",
      relationTo: "blogTags",
      hasMany: true,
    },
    {
      name: "meta",
      label: "Page Meta",
      type: "group",
      fields: [
        {
          name: "title",
          label: "Title",
          type: "text",
        },
        {
          name: "description",
          label: "Description",
          type: "textarea",
        },
        {
          name: "canonical_url",
          label: "Canonical Url",
          type: "text",
        },
      ],
    },
    {
      name: "createdBy",
      type: "relationship",
      relationTo: "users",
      hooks: {
        beforeChange: [setAuthor],
      },
      admin: {
        hidden: true,
      },
    },
    {
      name: "updatedBy",
      type: "relationship",
      relationTo: "users",
      hooks: {
        beforeChange: [setAuthor],
      },
      admin: {
        hidden: true,
      },
    },
  ],
  admin: {
    hideAPIURL: true,
    group: "Blogs",
    useAsTitle: "title",
  },
  access: {
    read: () => true,
  },
};
