interface MetaTags {
  title?: string;
  keywords?: string;
  description?: string;
  url?: string;
  image?: string;
  robots?: string;
}

interface MetaObject {
  title?: string;
  meta: Record<string, { name: string; content: string }>;
  link: Record<string, { rel?: string; href?: string }>;
}

export default function meta(metaTags: MetaTags): MetaObject {
  if (!metaTags) {
    return { meta: {}, link: {} };
  }

  const { title, keywords, description, url, image, robots } = metaTags;
  const defaultImage = `${process.env.APP_HOST}/images/logo_233x233.png`;

  const createMetaTag = (name: string, content: string) => ({ name, content });

  const metaObj: MetaObject = {
    title,
    meta: {},
    link: {},
  };

  if (title) {
    Object.assign(metaObj.meta, {
      ogTitle: createMetaTag('og:title', title),
      twitterTitle: createMetaTag('twitter:title', title),
    });
  }

  if (keywords) {
    metaObj.meta.keywords = createMetaTag('keywords', keywords);
  }

  if (description) {
    Object.assign(metaObj.meta, {
      description: createMetaTag('description', description),
      ogDescription: createMetaTag('og:description', description),
      twitterDescription: createMetaTag('twitter:description', description),
    });
  }

  if (url) {
    Object.assign(metaObj.meta, {
      ogUrl: createMetaTag('og:url', url),
      twitterUrl: createMetaTag('twitter:url', url),
    });
    metaObj.link.canonical = { rel: 'canonical', href: url };
  }

  Object.assign(metaObj.meta, {
    ogImage: createMetaTag('og:image', image || defaultImage),
    twitterImage: createMetaTag('twitter:image', image || defaultImage),
    twitterCard: createMetaTag('twitter:card', 'summary_large_image'),
    ogType: createMetaTag('og:type', 'website'),
  });

  if (robots) {
    metaObj.meta.robots = createMetaTag('robots', robots);
  }

  return metaObj;
}
