import Content from "@/components/dashboard/Content";
import { defineAbilitiesFor } from "@/lib/ability";
import { getUser } from "@/lib/auth";
import { getStateInfo } from "@/lib/getStateInfo";
import { fetchReq } from "@/lib/req";
import { removeToken } from "@/utils";
import { cookies, headers } from "next/headers";
import { redirect } from "next/navigation";

export default async function Dashboard({ searchParams }) {
  const { matchedCity } = getStateInfo();
  const user = await getUser();
  const ability = defineAbilitiesFor(user);
  const cookieStore = cookies();
  const token = cookieStore.get("access_token");
  const userInfo = cookieStore.get("userInfo");

  if (!ability.can("access", "Dashboard")) {
    removeToken();
    return redirect("/login");
  }

  const response = await fetchReq(
    `https://back-dev.clinic-pro.ir/api/v1/user-profile/${JSON.parse(userInfo?.value).uuid}`,
    {
      headers: {
        Authorization: `Bearer ${token.value}`,
      },
    }
  );

  const userAgent = headers().get("user-agent") || "";
  const isMobile = /Mobi|Android/i.test(userAgent);

  return (
    <Content
      dataUser={response}
      logged={token.value}
      params={searchParams}
      matchedCity={matchedCity}
      initialTurnsDetails={isMobile}
      userInfo={JSON.parse(userInfo.value || {})}
    />
  );
}
