"use server";
import NextCrypto from "next-crypto";

import { fetchData, fetchDataWithToken } from "../api-fetcher";
import { baseUrlAuth, cookieObject, tokenSecret } from "../basics";
import { cookies } from "next/headers";

// import { setAvailableEvents } from "../events/available";

const loginEndpoint = `${baseUrlAuth}/authentication/login`;
const loginSelectEndpoint = `${baseUrlAuth}/authentication/select`;

console.log("loginEndpoint", loginEndpoint);
console.log("loginSelectEndpoint", loginSelectEndpoint);

interface LoginViaAccessKeys {
  accessKey: string;
  password: string;
  rememberMe: boolean;
}

interface LoginSelectEmployee {
  company_uu_id: string;
}

interface LoginSelectOccupant {
  build_living_space_uu_id: any;
}

async function loginViaAccessKeys(payload: LoginViaAccessKeys) {
  try {
    const cookieStore = await cookies();
    const nextCrypto = new NextCrypto(tokenSecret);

    const response = await fetchData(
      loginEndpoint,
      {
        access_key: payload.accessKey,
        password: payload.password,
        remember_me: payload.rememberMe,
      },
      "POST",
      false
    );
    console.log("response", response);
    if (response.status === 200 || response.status === 202) {
      const loginRespone = response?.data;
      const accessToken = await nextCrypto.encrypt(loginRespone.access_token);
      const accessObject = await nextCrypto.encrypt(
        JSON.stringify({
          userType: loginRespone.user_type,
          selectionList: loginRespone.selection_list,
        })
      );
      const userProfile = await nextCrypto.encrypt(
        JSON.stringify(loginRespone.user)
      );

      cookieStore.set({
        name: "accessToken",
        value: accessToken,
        ...cookieObject,
      });
      console.log("accessObject", accessObject);

      cookieStore.set({
        name: "accessObject",
        value: accessObject,
        ...cookieObject,
      });
      cookieStore.set({
        name: "userProfile",
        value: JSON.stringify(userProfile),
        ...cookieObject,
      });
      try {
        return {
          completed: true,
          message: "Login successful",
          status: 200,
          data: loginRespone,
        };
      } catch (error) {
        console.error("JSON parse error:", error);
        return {
          completed: false,
          message: "Login NOT successful",
          status: 401,
          data: "{}",
        };
      }
    }

    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: LoginSelectEmployee) {
  const cookieStore = await cookies();
  const nextCrypto = new NextCrypto(tokenSecret);

  const selectResponse: any = await fetchDataWithToken(
    loginSelectEndpoint,
    {
      company_uu_id: payload.company_uu_id,
    },
    "POST",
    false
  );
  if (selectResponse.status === 200 || selectResponse.status === 202) {
    const usersSelection = await nextCrypto.encrypt(
      JSON.stringify({
        company_uu_id: payload.company_uu_id,
        user_type: "employee",
      })
    );
    cookieStore.set({
      name: "userSelection",
      value: usersSelection,
      ...cookieObject,
    });
  }
  return selectResponse;
}

async function loginSelectOccupant(payload: LoginSelectOccupant) {
  const build_living_space_uu_id = payload.build_living_space_uu_id;
  const cookieStore = await cookies();
  const nextCrypto = new NextCrypto(tokenSecret);
  const selectResponse: any = await fetchDataWithToken(
    loginSelectEndpoint,
    {
      build_living_space_uu_id: build_living_space_uu_id,
    },
    "POST",
    false
  );

  if (selectResponse.status === 200) {
    const usersSelection = await nextCrypto.encrypt(
      JSON.stringify({
        // company_uu_id: {
        //   build_part_uu_id: payload.build_part_uu_id,
        //   occupant_uu_id: payload.occupant_uu_id,
        //   build_id: selectedBuilding,
        // },
        build_living_space_uu_id: build_living_space_uu_id,
        user_type: "occupant",
      })
    );
    cookieStore.set({
      name: "userSelection",
      value: usersSelection,
      ...cookieObject,
    });
    // await setAvailableEvents();
  }
  return selectResponse;
}

export { loginViaAccessKeys, loginSelectEmployee, loginSelectOccupant };
