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

export const Projects: CollectionConfig = {
  slug: "projects",
  access: { read: () => true },
  admin: {
    useAsTitle: "title",
    defaultColumns: ["title", "status", "featured", "sortOrder", "year"],
    group: "Content",
  },
  hooks: {
    beforeValidate: [
      ({ data }) => {
        if (data && !data.slug && data.title) {
          data.slug = (data.title as string)
            .toLowerCase()
            .replace(/[^a-z0-9]+/g, "-")
            .replace(/(^-|-$)/g, "");
        }
        return data;
      },
    ],
  },
  fields: [
    { name: "title", type: "text", required: true },
    { name: "slug", type: "text", required: true, unique: true, index: true },
    { name: "summary", type: "textarea", required: true },
    {
      name: "status",
      type: "select",
      defaultValue: "active",
      required: true,
      options: [
        { label: "Active", value: "active" },
        { label: "Archived", value: "archived" },
        { label: "Prototype", value: "prototype" },
        { label: "Production", value: "production" },
      ],
    },
    { name: "year", type: "number" },
    { name: "heroImage", type: "upload", relationTo: "media" },
    {
      name: "gallery",
      type: "array",
      fields: [
        { name: "image", type: "upload", relationTo: "media", required: true },
        { name: "caption", type: "text" },
      ],
    },
    {
      name: "tech",
      type: "array",
      fields: [{ name: "label", type: "text" }],
    },
    { name: "role", type: "text" },
    {
      name: "links",
      type: "array",
      fields: [
        { name: "label", type: "text", required: true },
        { name: "href", type: "text", required: true },
        {
          name: "type",
          type: "select",
          options: [
            { label: "Live", value: "live" },
            { label: "Repo", value: "repo" },
            { label: "Docs", value: "docs" },
            { label: "Write-up", value: "writeup" },
          ],
        },
      ],
    },
    { name: "body", type: "richText", editor: lexicalEditor({}) },
    { name: "featured", type: "checkbox", defaultValue: false },
    { name: "sortOrder", type: "number", defaultValue: 0 },
  ],
};
