import { useEffect, useState } from "react";
import { BoardSchema, BoardService } from "../../../client";
import { useProjectsContext } from "../../../contexts/ProjectsContext.tsx";
import { useSelector } from "react-redux";
import { RootState } from "../../../redux/store.ts";


const useBoards = () => {
    const { selectedProject } = useProjectsContext();
    const [boards, setBoards] = useState<BoardSchema[]>([]);
    const { isDealsViewer } = useSelector((state: RootState) => state.auth);

    const filterBoards = (boards: BoardSchema[]): BoardSchema[] => {
        if (isDealsViewer) {
            const SALES_DEPARTMENT_FF = 5;
            return boards.filter(board => board.id !== SALES_DEPARTMENT_FF);
        }
        return boards;
    };

    const refetchBoards = () => {
        if (!selectedProject) return;

        BoardService.getBoards({
            projectId: selectedProject.id,
        })
            .then(data => {
                setBoards(filterBoards(data.boards));
            })
            .catch(e => console.log(e));
    };

    useEffect(() => {
        refetchBoards();
    }, [selectedProject]);

    return {
        boards,
        refetchBoards,
    };
};

export default useBoards;
