import { CollectionConfig } from 'payload';
import { lexicalEditor, BlocksFeature } from '@payloadcms/richtext-lexical';
import { payloadBlocks } from '../blocks/allBlocks';

export const Pages: CollectionConfig = {
  slug: 'pages',
  admin: {
    useAsTitle: 'title',
    defaultColumns: ['title', 'slug', 'layout', '_status', 'updatedAt'],
  },
  versions: {
    drafts: true,
  },
  access: {
    read: ({ req: { user } }) => {
      if (process.env.NODE_ENV === 'development' || process.env.TARGET === 'staging') {
        return true;
      }
      if (user) {
        return true;
      }
      return {
        _status: {
          equals: 'published',
        },
      };
    },
  },
  fields: [
    {
      name: 'title',
      type: 'text',
      required: true,
      localized: true,
    },
    {
      name: 'slug',
      type: 'text',
      required: true,
      localized: true,
      admin: {
        position: 'sidebar',
        description: 'The URL slug for this locale (e.g. "impressum" for DE, "imprint" for EN).',
      },
    },
    {
      name: 'layout',
      type: 'select',
      defaultValue: 'default',
      options: [
        { label: 'Default (Article)', value: 'default' },
        { label: 'Full Bleed (Blocks Only)', value: 'fullBleed' },
      ],
      admin: {
        position: 'sidebar',
        description: 'Full Bleed pages render blocks edge-to-edge without a generic hero wrapper.',
      },
    },
    {
      name: 'excerpt',
      type: 'textarea',
      localized: true,
      admin: {
        position: 'sidebar',
      },
    },
    {
      name: 'featuredImage',
      type: 'upload',
      relationTo: 'media',
      admin: {
        position: 'sidebar',
      },
    },
    {
      type: 'collapsible',
      label: 'Redirect Settings',
      admin: {
        position: 'sidebar',
      },
      fields: [
        {
          name: 'redirectUrl',
          type: 'text',
          localized: true,
          admin: {
            description:
              'If set, visiting this page will immediately redirect the user to this URL (e.g. /de/terms).',
          },
        },
        {
          name: 'redirectPermanent',
          type: 'checkbox',
          defaultValue: true,
          admin: {
            description:
              'Check for a permanent (301) redirect. Uncheck for a temporary (302) redirect.',
          },
        },
      ],
    },
    {
      name: 'content',
      type: 'richText',
      localized: true,
      editor: lexicalEditor({
        features: ({ defaultFeatures }) => [
          ...defaultFeatures,
          BlocksFeature({
            blocks: payloadBlocks,
          }),
        ],
      }),
      required: true,
    },
  ],
};
