import type { ContentLinkPageProps } from '~/src/views/ContentLinkPage';
import type { GetServerSideProps } from 'next';

import { toNumber } from '~/lib/utils/number';
import { getFirstValue } from '~/src/components/NextApp/lib/serverImports';
import { withI18n } from '~/src/lib/i18n';
import { getContentLinkPreviewApi } from '~/src/lib/songwhipApi/contentLinks/get';
import { isUrlSafe } from '~/src/lib/utils/url';
import { ContentLinkPage } from '~/src/views/ContentLinkPage';

const notFoundRedirect = {
  redirect: {
    destination: '/not-found',
    permanent: false,
  },
};

export const getServerSideProps: GetServerSideProps<
  ContentLinkPageProps
> = async (ctx) => {
  const idString = getFirstValue(ctx.params?.id);
  const id = toNumber(idString);

  if (!id) return notFoundRedirect;

  try {
    const contentLink = await getContentLinkPreviewApi(id);

    if (!isUrlSafe(contentLink.destinationUrl)) return notFoundRedirect;

    return {
      props: {
        accountId: contentLink.accountId,
        contentLinkId: contentLink.id,
        url: new URL(contentLink.destinationUrl).href,
        ogTitle: contentLink.name,
        ogImageUrl: contentLink.image ?? contentLink.artists[0]?.image ?? null,
        shareUrl: `https://${contentLink.customLink.domain}${contentLink.customLink.path}`,
      },
    };
  } catch {
    return notFoundRedirect;
  }
};

export default withI18n(ContentLinkPage, ['contentLinkRedirect']);
