import { API_URL } from "@/core/constant";
import UpdateTicketForm from "@/ui/form/UpdateTicketForm";
import { cookies } from "next/headers";
interface PageProps {
  params: Promise<{ id: string }>;
}

async function getTicket(id: string) {
  const cookieStore = await cookies();
  const tokenCookie = cookieStore.get("userToken"); // گرفتن کوکی از درخواست کاربر
  const res = await fetch(`${API_URL}/ticket/get/${id}`, {
    cache: "no-store",
    credentials: "include",
    headers: {
      Cookie: `${tokenCookie?.name}=${tokenCookie?.value}`,
    },
  });
  if (!res.ok) {
    throw new Error("Error");
  }

  const data = await res.json();
  return data;
}

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({ params }: PageProps) {
  const { id } = await params;
  const getdata = await getTicket(id);
  
  const getdepartmentsdata = await getDepartmentsData();
  const getusersdata = await getUsersData();

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

  const selectedTicket = getdata?.data;
  return (
    <>
      {selectedTicket ? <UpdateTicketForm users={users} departments={departments} ticket={selectedTicket} /> : ""}
    </>
  );
}
