"use server";
import NextCrypto from "next-crypto";
import { fetchData, fetchDataWithToken } from "@/fetchers/fecther";
import { cookieObject, tokenSecret } from "@/fetchers/base";
import { urlLoginEndpoint, urlLoginSelectEndpoint, urlLogoutEndpoint } from "@/fetchers/index";

import { cookies } from "next/headers";
import { setNewCompleteToRedis, getCompleteFromRedis } from "@/fetchers/custom/context/complete/fetch";
import {
  defaultValuesHeader,
  defaultValuesMenu,
  defaultValuesOnline,
  defaultValuesPageConfig,
} from "@/fetchers/types/context";
import { retrievePageList } from "@/fetchers/mutual/cookies/token";
import { deleteAllCookies } from "@/fetchers/mutual/cookies/cookie-actions";
import { setMenuToRedis } from "@/fetchers/custom/context/page/menu/fetch";
import { LoginViaAccessKeys, LoginSelect } from "@/fetchers/types/login/validations";

async function logoutActiveSession() {
  const response = await fetchDataWithToken(urlLogoutEndpoint, {}, "GET", false);
  await deleteAllCookies();
  return response;
}

async function initRedis(loginRespone: any, firstSelection: any, accessToken: string, redisKey: string) {
  let alreadyAtRedis = null
  console.log("loginRespone", loginRespone)
  console.log("firstSelection", firstSelection)
  console.log("accessToken", accessToken)
  console.log("redisKey", redisKey)
  if (!alreadyAtRedis) {
    if (loginRespone.user_type.toUpperCase() === "EMPLOYEE") {
      const loginObjectToRedis = {
        online: { ...defaultValuesOnline, lastLogin: new Date(), userType: `${loginRespone.user_type}`.toUpperCase(), lang: loginRespone.user.person.country_code.toLowerCase() },
        pageConfig: defaultValuesPageConfig,
        menu: defaultValuesMenu,
        header: defaultValuesHeader,
        selection: { selectionList: loginRespone.selection_list, activeSelection: firstSelection },
        user: loginRespone.user,
        settings: { lastOnline: new Date(), token: accessToken },
        chatRoom: [],
        notifications: [],
        messages: [],
      }
      await setNewCompleteToRedis(loginObjectToRedis, redisKey);
    } else if (loginRespone.user_type.toUpperCase() === "OCCUPANT") {
      const loginObjectToRedis = {
        online: { ...defaultValuesOnline, lastLogin: new Date(), userType: `${loginRespone.user_type}`.toUpperCase(), lang: "tr" },
        pageConfig: defaultValuesPageConfig,
        menu: defaultValuesMenu,
        header: defaultValuesHeader,
        selection: { selectionList: loginRespone.selection_list, activeSelection: firstSelection },
        user: loginRespone.user,
        settings: { lastOnline: new Date(), token: accessToken },
        chatRoom: [],
        notifications: [],
        messages: [],
      }
      await setNewCompleteToRedis(loginObjectToRedis, redisKey);
    }
  }
}

async function initFirstSelection(firstSelection: any, userType: string) {
  if (userType === "EMPLOYEE") {
    const uuid = firstSelection.uuid;
    await loginSelectEmployee({ uuid });
  } else if (userType === "OCCUPANT") {
    const uuid = firstSelection.build_living_space_uu_id;
    await loginSelectOccupant({ uuid });
  }
}

async function loginViaAccessKeys(payload: LoginViaAccessKeys) {
  const cookieStore = await cookies();
  try {
    const response = await fetchData(
      urlLoginEndpoint,
      {
        access_key: payload.accessKey,
        password: payload.password,
        remember_me: payload.rememberMe,
      },
      "POST",
      false
    );
    await deleteAllCookies()
    if (response.status === 200 || response.status === 202) {

      const loginRespone: any = response?.data;

      let firstSelection = null

      if (loginRespone.user_type.toUpperCase() === "EMPLOYEE") {
        firstSelection = loginRespone.selection_list.find((item: any) => item.uu_id === loginRespone.selection_list[0].uu_id);
      } else if (loginRespone.user_type.toUpperCase() === "OCCUPANT") {
        const firstKeyOfSelectionList = Object.keys(loginRespone.selection_list)[0];
        firstSelection = loginRespone.selection_list[firstKeyOfSelectionList].occupants[0];
      }
      const nextCrypto = new NextCrypto(tokenSecret);
      const accessToken = await nextCrypto.encrypt(loginRespone.access_token);
      const userType = loginRespone.user_type.toUpperCase()
      const redisKey = `CLIENT:${userType}:${loginRespone.user.uuid}`;
      const redisKeyAccess = await nextCrypto.encrypt(redisKey);
      const usersSelection = await nextCrypto.encrypt(JSON.stringify({ selected: firstSelection, userType, redisKey }));

      await initRedis(loginRespone, firstSelection, accessToken, redisKey);

      cookieStore.set({
        name: "eys-zzz",
        value: accessToken,
        ...cookieObject,
      });
      cookieStore.set({
        name: "eys-yyy",
        value: redisKeyAccess,
        ...cookieObject,
      });
      cookieStore.set({
        name: "eys-sel",
        value: usersSelection,
        ...cookieObject,
      });

      try {
        return {
          completed: true,
          message: "Login successful",
          status: 200,
          data: {
            userType,
            firstSelection,
          },
        };
      } catch (error) {
        console.error("JSON parse error:", error);
        return {
          completed: false,
          message: "Login NOT successful",
          status: 401,
          data: {
            userType,
            firstSelection,
          },
        };
      }
    }

    return {
      completed: false,
      // error: response.error || "Login failed",
      // message: response.message || "Authentication failed",
      status: response.status || 500,
    };
  } catch (error) {
    console.error("Login error:", error);
    return {
      completed: false,
      // error: error instanceof Error ? error.message : "Login error",
      // message: "An error occurred during login",
      status: 500,
    };
  }
}

async function loginSelectEmployee(payload: LoginSelect) {
  const employeeUUID = payload.uuid;
  const selectResponse: any = await fetchDataWithToken(urlLoginSelectEndpoint, { uuid: employeeUUID }, "POST", false);
  console.log("selectResponse", selectResponse)
  if (selectResponse.status === 200 || selectResponse.status === 202) {
    try {
      console.log("selectResponse", selectResponse)
    } catch (error) { }
  }
  return selectResponse;
}

async function loginSelectOccupant(payload: LoginSelect) {
  const livingSpaceUUID = payload.uuid;
  const selectResponse: any = await fetchDataWithToken(urlLoginSelectEndpoint, { uuid: livingSpaceUUID }, "POST", false);
  console.log("selectResponse", selectResponse)
  if (selectResponse.status === 200 || selectResponse.status === 202) {
    try {
      console.log("selectResponse", selectResponse)
    } catch (error) { }
  }
  return selectResponse;
}

export {
  loginViaAccessKeys,
  initFirstSelection,
  loginSelectEmployee,
  loginSelectOccupant,
  logoutActiveSession,
};
