"use server";
import { redirect } from "next/navigation";

import { updateBuild } from "@/apicalls/building/build";
import { retrieveAvailableEndpoint } from "@/apicalls/checkEndpoint";
import { checkAccessTokenIsValid } from "@/apicalls/cookies/token";
import { decryptQuery, defaultPagination } from "@/apicalls/test";
import { retrieveHeadersAndValidationByEndpoint } from "@/apicalls/validations/validations";

import { RetrieveInputByType } from "@/hooks/renderInputWithValidation";

import React from "react";
import UpdatePageComponent from "@/components/commons/UpdatePage";

export default async function BuildingUpdatePage({
  searchParams,
}: {
  searchParams: any;
}) {
  if (!(await checkAccessTokenIsValid())) {
    redirect("/login/email");
  }

  const buildKey = "building/update";
  const searchParamsKeys = await searchParams;
  const endpointUrl = "building/build/update/{build_uu_id}";
  if (!searchParamsKeys?.q) {
    redirect(`/${buildKey}`);
  }
  const queryEncrypt = await decryptQuery(searchParamsKeys?.q);
  const endpointAvailable = await retrieveAvailableEndpoint(endpointUrl);
  const validateAndHeaders = await retrieveHeadersAndValidationByEndpoint({
    endpoint: endpointUrl,
  });
  const validator = validateAndHeaders?.validated || {};
  const headers = validateAndHeaders?.headers || {};
  console.log("endpointAvailable", endpointAvailable);
  console.log("validator", validator);
  console.log("headers", headers);
  console.log("queryEncrypt", queryEncrypt);

  return (
    <div>
      <h1>Update Building</h1>
      <h1>{JSON.stringify(queryEncrypt)}</h1>

      <UpdatePageComponent
        validator={validator}
        headers={headers}
        queryEncrypt={queryEncrypt}
        commitFunction={updateBuild}
      />
    </div>
  );
}
