import { fetchProjectCategories, fetchProjects } from "@/app/api/projects";
import React from "react";
import ProjectSearch from "./ProjectSearch";
import ProjectSearchLoading from "./ProjectSearchLoading";
import { fetchUserAbilities, fetchUserStaff } from "@/app/utils/fetchUtil";
import { authOptions } from "@/config/authConfig";
import { getServerSession } from "next-auth";
import { VIEW_ALL_PROJECTS } from "@/middleware";
import { fetchTeam } from "@/app/api/team";
import { fetchAllCustomers } from "@/app/api/customer";

interface SubComponents {
  Loading: typeof ProjectSearchLoading;
}

const ProjectSearchWrapper: React.FC & SubComponents = async () => {
  const projectCategories = await fetchProjectCategories();
  const userStaff = await fetchUserStaff();
  const teamId = userStaff?.teamId;
  const projects = await fetchProjects();
  const teams = await fetchTeam();
  const customers = await fetchAllCustomers();

  const abilities = await fetchUserAbilities();
  const isViewAllProjectRight = [VIEW_ALL_PROJECTS].some((ability) =>
    abilities.includes(ability),
  );

  let filteredProjects = projects;
  if (!isViewAllProjectRight) {
    filteredProjects = projects.filter((project) => project.teamId === teamId );
    if (teamId == 1){
      filteredProjects = projects.filter((project) => project.teamId === teamId || project.team === "ST");
    }  
  }

  return (
    <ProjectSearch
      projects={filteredProjects}
      projectCategories={projectCategories}
      abilities={abilities}
      teams={teams}
      customers={customers}
    />
  );
};

ProjectSearchWrapper.Loading = ProjectSearchLoading;

export default ProjectSearchWrapper;
