import { Metadata } from "next";
import { redirect } from "next/navigation";

import { Options } from "@/types/options/options-data-types";
import { LifeProfileSchema } from "@/types/profile/profile-update-schema";
import { CORE_ENDPOINTS } from "@/constants/api-mappings/external-api-mapping";
import { getProfileData, getOptions } from "@/services/general-actions";
import Life from "@/components/pages/participant/profile/tabs/life-choices";
import { retrieveUserToken } from "@/lib/user-session";
import { INTERNAL_PAGES } from "@/constants/pages-mapping/internal-pages-mapping";

export const metadata: Metadata = {
  title: "Life choices | Profile",
};

export default async function LifeProfilePage() {
  const userToken = await retrieveUserToken();

  if (!userToken) {
    redirect(INTERNAL_PAGES.participant.login);
  }

  const participantData = await getProfileData(userToken);

  const { id: userId } = participantData;

  const optionEndpoints = [
    CORE_ENDPOINTS.options.maritalStatus,
    CORE_ENDPOINTS.options.household,
    CORE_ENDPOINTS.options.education,
    CORE_ENDPOINTS.options.driving,
  ];

  const [
    maritalStatusOptions,
    householdOptions,
    educationOptions,
    drivingOptions,
  ] = await Promise.all(
    optionEndpoints.map((endpoint) => getOptions(endpoint, userToken))
  );

  const childrenOptions: Options = [
    { id: 1, title: "Yes" },
    { id: 2, title: "No" },
  ];

  const options = {
    maritalStatusOptions,
    childrenOptions,
    householdOptions,
    educationOptions,
    drivingOptions,
  };

  const { personalInformation } = participantData;

  const profileData: LifeProfileSchema = {
    maritalStatusId: personalInformation.maritalStatusId,
    hasChildren: personalInformation.hasChildren,
    householdIds: personalInformation.householdIds,
    educationLevelId: personalInformation.educationLevelId,
    drivingOptionsIds: personalInformation.drivingOptionsIds,
  };

  return <Life options={options} profileData={profileData} userId={userId} />;
}
