import { ContentBlock } from "@/blocks/Content";
import { FormBlock } from "@/blocks/Form";
import formatSlug from "@/utils/payload/formatSlug";
import setAuthor from "@/utils/payload/setAuthor";
import { CollectionConfig } from "payload";

export const Pages: CollectionConfig = {
  slug: "pages",
  versions: {
    drafts: {
      validate: true,
    },
  },
  fields: [
    {
      name: "title",
      label: "Page Title",
      type: "text",
      required: true,
    },
    {
      name: "hero_img",
      label: "Hero Image",
      type: "upload",
      relationTo: "media",
    },
    {
      name: "slug",
      label: "Page Slug",
      type: "text",
      hooks: {
        beforeValidate: [formatSlug("title")],
      },
    },
    {
      name: "layout",
      label: "Page Layout",
      type: "blocks",
      minRows: 1,
      blocks: [ContentBlock, FormBlock],
    },
    {
      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: "General",
    useAsTitle: "title",
  },
};
