import { jsonToGraphQLQuery } from 'json-to-graphql-query';

import { AboutUsPageData } from '@/app/api-utlities/@types/about-us';
import { MainPageData } from '@/app/api-utlities/@types/main';
import {
  presentDiscounts,
  presentHistoryItems,
  presentJobs,
  presentPartners,
  presentReviews,
  presentStations,
  presentTeamMembers,
} from '@/app/api-utlities/presenters';
import { aboutUsPageRequest } from '@/app/api-utlities/requests/about-us-page.request';
import { mainPageRequest } from '@/app/api-utlities/requests/main-page.request';

import { taylorAPI } from '@/shared/api/taylor-api';

export const mainPageApi = taylorAPI.injectEndpoints({
  endpoints: (builder) => ({
    fetchMainPageContent: builder.query<MainPageData, void>({
      query: () => ({
        url: '',
        method: 'POST',
        body: {
          query: jsonToGraphQLQuery({ query: mainPageRequest }),
        },
      }),

      transformResponse: (response: any) => {
        return {
          partners: presentPartners(response.data._partners),
          jobs: presentJobs(response.data._vacancies),
          discounts: presentDiscounts(response.data._akcii),
          stations: presentStations(response.data._azs),
        };
      },
    }),

    fetchAboutUsPageContent: builder.mutation<AboutUsPageData, void>({
      query: () => ({
        url: '',
        method: 'POST',
        body: {
          query: jsonToGraphQLQuery({ query: aboutUsPageRequest }),
        },
      }),

      transformResponse: (response: any) => {
        return {
          team: presentTeamMembers(response.data._komanda),
          history: presentHistoryItems(response.data._istoriya),
          stations: presentStations(response.data._azs),
          reviews: presentReviews(response.data._otzyvy),
        };
      },
    }),
  }),
});
