import { type ReactNode } from "react";
import Image from "next/image";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { SuccessApiResponse } from "../../../types/api-response";
import { ProfileResponse } from "../../../hooks/features/profile/useProfileFetch";
import StoreHydrator from "../../../components/StoreHydrator";

async function getProfile(): Promise<SuccessApiResponse<ProfileResponse>> {
  const cookieStore = await cookies();
  const token = cookieStore.get("accessToken")?.value;

  const res = await fetch(`${process.env.APP_URL}/profile`, {
    headers: { Authorization: `Bearer ${token}` },
    cache: "no-store",
  });

  if (res.status === 401) {
    // remove cookies as well
    redirect("/");
  }

  if (!res.ok) {
    redirect("/");
  }

  const apiKeyRes = await fetch(`${process.env.APP_URL}/api-keys/current`, {
    headers: { Authorization: `Bearer ${token}` },
    cache: "no-store",
  });

  const apiKeys = await apiKeyRes.json();

  const obj = await res.json();

  obj.data.apiKey = apiKeys?.data?.apiKey;


  return obj as Promise<SuccessApiResponse<ProfileResponse>>;
}

export default async function UserLayout({
  children,
}: {
  children: ReactNode;
}) {
  const profile = await getProfile();

  return (
    <div className="relative overflow-hidden">
      <div className="absolute inset-0 -z-10">
        <Image
          src="/images/dashboard-bg.svg"
          alt="Hero Background"
          fill
          priority
          className="object-cover"
        />
      </div>
      <StoreHydrator profile={profile.data} />
      <main className="pt-36 pb-8 sm:pt-40 sm:pb-8 md:pt-48 md:pb-section 2xl:pt-56 px-4">
        {children}
      </main>
    </div>
  );
}
