import React from 'react';
import { ParsedUrlQuery } from 'querystring';
import { RankingProps, RankingTeamData } from '../src/model/components/ranking';
import Layout from '../src/components/layout/Layout';
import RankingPage from '../src/components/pages/ranking/RankingPage';
import withUserSSR from '../src/utils/ssr/withSSRUser';
import getTeams from '../src/utils/api/getTeams';

const index: React.FC<RankingProps> = ({ teams, myTeam }) => (
  <Layout title="Ranking">
    <RankingPage teams={teams} myTeam={myTeam} />
  </Layout>
);

export const getServerSideProps = withUserSSR<RankingProps, ParsedUrlQuery>(
  async (_, user) => {
    const teams = await getTeams();
    const rankingTeamData: RankingTeamData[] = teams.map((team) => {
      return {
        id: team.id,
        name: team.name,
        totalScore: team.totalScore || 0,
        extraPoints: !!team.extraPoints,
      };
    });

    return {
      props: {
        teams: rankingTeamData.sort(
          (ant, act) => act.totalScore - ant.totalScore,
        ),
        myTeam: {
          id: user.team.id,
          name: user.team.name,
          totalScore: user.team.totalScore,
          extraPoints: !!user.team.extraPoints,
        },
      },
    };
  },
);

export default index;
