import { CollectionSlug, PayloadRequest } from 'payload';

const collectionPrefixMap: Partial<Record<CollectionSlug, string>> = {
  posts: '/blog',
  pages: '',
};

type Props = {
  collection: keyof typeof collectionPrefixMap;
  slug: string;
  req: PayloadRequest;
  postType?: 'blog' | 'hub';
};

export const generatePreviewPath = ({ collection, slug, postType }: Props) => {
  // Allow empty strings, e.g. for the homepage
  if (slug === undefined || slug === null) {
    return null;
  }

  // For posts collection, determine path based on postType
  let path = `${collectionPrefixMap[collection]}/${slug}`;
  if (collection === 'posts' && postType) {
    const basePath = postType === 'hub' ? '/hub' : '/blog';
    path = `${basePath}/${slug}`;
  }

  const encodedParams = new URLSearchParams({
    slug,
    collection,
    path,
    previewSecret: process.env.PREVIEW_SECRET || '',
  });

  const url = `/next/preview?${encodedParams.toString()}`;

  return url;
};
