import { API_URL } from "@/core/constant";
import TicketForm from "@/ui/form/TicketForm";
import { cookies } from "next/headers";

async function getDepartmentsData() {
  const cookieStore = await cookies();
  const tokenCookie = cookieStore.get("userToken"); // گرفتن کوکی از درخواست کاربر

  const res = await fetch(`${API_URL}/department/all`, {
    cache: "no-cache",
    credentials: "include",
    headers: {
      "Content-Type": "application/json",
      Cookie: `${tokenCookie?.name}=${tokenCookie?.value}`,
    },
  });

  if (!res.ok) {
    throw new Error("خطا در واكشي ديتاي واحد ها");
  }

  const data = await res.json();

  return data;
}

async function getUsersData() {
  const cookieStore = await cookies();
  const tokenCookie = cookieStore.get("userToken"); // گرفتن کوکی از درخواست کاربر
  const res = await fetch(`${API_URL}/user/all`, {
    cache: "no-cache",
    credentials: "include",
    headers: {
      "Content-Type": "application/json",
      Cookie: `${tokenCookie?.name}=${tokenCookie?.value}`,
    },
  });

  if (!res.ok) {
    throw new Error("خطا در واكشي ديتاي واحد ها");
  }

  const data = await res.json();

  return data;
}

export default async function Page() {
  const getdepartmentsdata = await getDepartmentsData();
  const getusersdata = await getUsersData();

  const departments = getdepartmentsdata?.data;
  const users = getusersdata?.data;

  return (
    <>
      <TicketForm departments={departments} users={users} />
    </>
  );
}
