import App, {AppProps} from 'next/app';
import {SessionProvider} from "next-auth/react";
import {config, library} from "@fortawesome/fontawesome-svg-core";
import '@fortawesome/fontawesome-svg-core/styles.css';
import {faBagShopping, faRightToBracket, faUserPlus} from "@fortawesome/free-solid-svg-icons";
import axios from "axios";
import delve from 'dlv';

import {environment} from "../environments/environment";
import './styles.css';

config.autoAddCss = false;

library.add(faRightToBracket);
library.add(faUserPlus);
library.add(faBagShopping);

interface CustomAppProps extends AppProps {
  menuHeader: object[],
  menuFooter: object[],
  page: object,
  seo: object,
}

const getPageMetadata = async (path) => {
  try {
    return await axios.get(`${environment.strapiApiUrl}/pages?filters[slug]=${path === '/' ? 'home' : path.slice(1, path.length)}&populate=deep`);
  } catch (e) {
    console.error(e);
    return Promise.resolve({})
  }
}


const CustomApp = ({Component, pageProps: {session, ...pageProps}, menuFooter, menuHeader, seo}: CustomAppProps) => {
  pageProps = {...pageProps, menuFooter, menuHeader, seo};
  return (
    <SessionProvider session={session}>
      <Component {...pageProps} />
    </SessionProvider>
  );
}

CustomApp.getInitialProps = async (context) => {
  const appProps = await App.getInitialProps(context);
  const path = context.router.pathname;
  const menuHeader = await axios.get(`${environment.strapiApiUrl}/menus/1?nested&populate=deep`);
  const menuFooter = await axios.get(`${environment.strapiApiUrl}/menus/2?nested&populate=deep`);
  const page = await getPageMetadata(path);

  return {
    ...appProps,
    menuHeader: delve(menuHeader, 'data.data.attributes.items.data', []),
    menuFooter: delve(menuFooter, 'data.data.attributes.items.data', []),
    page: delve(page, "data.data.0.attributes", {}),
    seo: delve(page, "data.data.0.attributes.seo", {})
  }
}

export default CustomApp;
