"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/hooks/useSendActivity.ts
var useSendActivity_exports = {};
__export(useSendActivity_exports, {
  useSendActivity: () => useSendActivity
});
module.exports = __toCommonJS(useSendActivity_exports);
var import_react2 = require("react");
var import_dayjs = __toESM(require("dayjs"));

// src/utils/categoryDataUtils.ts
async function fetchStudentsByFilters(apiClient, filters) {
  if ((!filters.schoolIds || filters.schoolIds.length === 0) && (!filters.schoolYearIds || filters.schoolYearIds.length === 0) && (!filters.classIds || filters.classIds.length === 0)) {
    return [];
  }
  const response = await apiClient.post("/students/filters", {
    ...filters.schoolIds && filters.schoolIds.length > 0 && {
      schoolIds: filters.schoolIds
    },
    ...filters.schoolYearIds && filters.schoolYearIds.length > 0 && {
      schoolYearIds: filters.schoolYearIds
    },
    ...filters.classIds && filters.classIds.length > 0 && {
      classIds: filters.classIds
    }
  });
  return response.data.data.students || [];
}
async function loadCategoriesData(apiClient, existingCategories) {
  if (existingCategories.length > 0) {
    return existingCategories;
  }
  const [schoolsResponse, schoolYearsResponse, classesResponse] = await Promise.all([
    apiClient.get(
      "/school"
    ),
    apiClient.get("/schoolYear"),
    apiClient.get("/classes")
  ]);
  const schools = schoolsResponse.data.data.schools;
  const schoolYears = schoolYearsResponse.data.data.schoolYears;
  const classes = classesResponse.data.data.classes;
  const transformedCategories = [
    {
      key: "escola",
      label: "Escola",
      itens: schools.map((s) => ({ id: s.id, name: s.companyName })),
      selectedIds: []
    },
    {
      key: "serie",
      label: "S\xE9rie",
      dependsOn: ["escola"],
      filteredBy: [{ key: "escola", internalField: "schoolId" }],
      itens: schoolYears.map((sy) => ({
        id: sy.id,
        name: sy.name,
        schoolId: sy.schoolId
      })),
      selectedIds: []
    },
    {
      key: "turma",
      label: "Turma",
      dependsOn: ["serie"],
      filteredBy: [{ key: "serie", internalField: "schoolYearId" }],
      itens: classes.map((c) => ({
        id: c.id,
        name: c.name,
        schoolYearId: c.schoolYearId
      })),
      selectedIds: []
    },
    {
      key: "students",
      label: "Alunos",
      dependsOn: ["turma"],
      filteredBy: [
        { key: "escola", internalField: "escolaId" },
        { key: "serie", internalField: "serieId" },
        { key: "turma", internalField: "turmaId" }
      ],
      // Students will be loaded dynamically based on selections
      itens: [],
      selectedIds: []
    }
  ];
  return transformedCategories;
}

// src/utils/useDynamicStudentFetching.ts
var import_react = require("react");
function extractSelectedIds(updatedCategories) {
  const escolaCategory = updatedCategories.find((c) => c.key === "escola");
  const serieCategory = updatedCategories.find((c) => c.key === "serie");
  const turmaCategory = updatedCategories.find((c) => c.key === "turma");
  const studentsCategory = updatedCategories.find((c) => c.key === "students");
  return {
    schoolIds: escolaCategory?.selectedIds || [],
    schoolYearIds: serieCategory?.selectedIds || [],
    classIds: turmaCategory?.selectedIds || [],
    studentsCategory
  };
}
function detectSelectionChanges(previousSelections, currentSelections) {
  const isInitialState = previousSelections.schoolIds.length === 0 && previousSelections.schoolYearIds.length === 0 && previousSelections.classIds.length === 0;
  const arraysEqual = (a, b) => {
    if (a.length !== b.length) return false;
    return a.every((id) => b.includes(id)) && b.every((id) => a.includes(id));
  };
  const schoolIdsChanged = isInitialState || !arraysEqual(previousSelections.schoolIds, currentSelections.schoolIds);
  const schoolYearIdsChanged = isInitialState || !arraysEqual(
    previousSelections.schoolYearIds,
    currentSelections.schoolYearIds
  );
  const classIdsChanged = isInitialState || !arraysEqual(previousSelections.classIds, currentSelections.classIds);
  const shouldFetchStudents = schoolIdsChanged || schoolYearIdsChanged || classIdsChanged;
  return {
    schoolIdsChanged,
    schoolYearIdsChanged,
    classIdsChanged,
    shouldFetchStudents
  };
}
function transformStudentsToItems(students) {
  return students.map((s) => ({
    id: `${s.userInstitutionId}-${s.class.id}`,
    name: s.name,
    classId: String(s.class.id),
    schoolId: String(s.school.id),
    schoolYearId: String(s.schoolYear.id),
    studentId: s.id,
    userInstitutionId: s.userInstitutionId,
    escolaId: String(s.school.id),
    serieId: String(s.schoolYear.id),
    turmaId: String(s.class.id)
  }));
}
function updateCategoriesWithStudents(updatedCategories, studentItems) {
  return updatedCategories.map(
    (cat) => cat.key === "students" ? { ...cat, itens: studentItems } : cat
  );
}
function clearStudentsFromCategories(updatedCategories) {
  return updatedCategories.map(
    (cat) => cat.key === "students" ? { ...cat, itens: [] } : cat
  );
}
function useDynamicStudentFetching(setCategories, options = {}) {
  const {
    apiClient,
    fetchStudentsByFilters: customFetchStudents,
    onError
  } = options;
  const previousSelectionsRef = (0, import_react.useRef)({
    schoolIds: [],
    schoolYearIds: [],
    classIds: []
  });
  const fetchRequestId = (0, import_react.useRef)(0);
  const buildStudentFilters = (0, import_react.useCallback)(
    (selectedSchoolIds, selectedSchoolYearIds, selectedClassIds) => ({
      schoolIds: selectedSchoolIds.length > 0 ? selectedSchoolIds : void 0,
      schoolYearIds: selectedSchoolYearIds.length > 0 ? selectedSchoolYearIds : void 0,
      classIds: selectedClassIds.length > 0 ? selectedClassIds : void 0
    }),
    []
  );
  const fetchWithCustomFunction = (0, import_react.useCallback)(
    async (selectedSchoolIds, selectedSchoolYearIds, selectedClassIds, localRequestId) => {
      if (!customFetchStudents) {
        return null;
      }
      const filters = buildStudentFilters(
        selectedSchoolIds,
        selectedSchoolYearIds,
        selectedClassIds
      );
      const students = await customFetchStudents(filters);
      if (localRequestId !== fetchRequestId.current) {
        return null;
      }
      return students;
    },
    [customFetchStudents, buildStudentFilters]
  );
  const fetchWithApiClient = (0, import_react.useCallback)(
    async (selectedSchoolIds, selectedSchoolYearIds, selectedClassIds, localRequestId) => {
      if (!apiClient) {
        return null;
      }
      const filters = buildStudentFilters(
        selectedSchoolIds,
        selectedSchoolYearIds,
        selectedClassIds
      );
      const students = await fetchStudentsByFilters(apiClient, filters);
      if (localRequestId !== fetchRequestId.current) {
        return null;
      }
      return students;
    },
    [apiClient, buildStudentFilters]
  );
  const performStudentFetch = (0, import_react.useCallback)(
    async (selectedSchoolIds, selectedSchoolYearIds, selectedClassIds, localRequestId) => {
      const students = await fetchWithCustomFunction(
        selectedSchoolIds,
        selectedSchoolYearIds,
        selectedClassIds,
        localRequestId
      );
      if (students !== null) {
        return students;
      }
      return fetchWithApiClient(
        selectedSchoolIds,
        selectedSchoolYearIds,
        selectedClassIds,
        localRequestId
      );
    },
    [fetchWithCustomFunction, fetchWithApiClient]
  );
  const handleSuccessfulFetch = (0, import_react.useCallback)(
    (students, updatedCategories, localRequestId) => {
      if (localRequestId !== fetchRequestId.current) {
        return false;
      }
      const studentItems = transformStudentsToItems(students);
      const finalCategories = updateCategoriesWithStudents(
        updatedCategories,
        studentItems
      );
      setCategories(finalCategories);
      return true;
    },
    [setCategories]
  );
  const handleFetchError = (0, import_react.useCallback)(
    (error, updatedCategories, localRequestId) => {
      console.error("Error fetching students:", error);
      if (onError && error instanceof Error) {
        onError(error);
      }
      if (localRequestId !== fetchRequestId.current) {
        return false;
      }
      const finalCategories = clearStudentsFromCategories(updatedCategories);
      setCategories(finalCategories);
      return true;
    },
    [onError, setCategories]
  );
  const handleCategoriesChange = (0, import_react.useCallback)(
    async (updatedCategories) => {
      if (!customFetchStudents && !apiClient) {
        setCategories(updatedCategories);
        return;
      }
      const {
        schoolIds: selectedSchoolIds,
        schoolYearIds: selectedSchoolYearIds,
        classIds: selectedClassIds,
        studentsCategory
      } = extractSelectedIds(updatedCategories);
      const previousSelections = previousSelectionsRef.current;
      const { shouldFetchStudents } = detectSelectionChanges(
        previousSelections,
        {
          schoolIds: selectedSchoolIds,
          schoolYearIds: selectedSchoolYearIds,
          classIds: selectedClassIds
        }
      );
      previousSelectionsRef.current = {
        schoolIds: [...selectedSchoolIds],
        schoolYearIds: [...selectedSchoolYearIds],
        classIds: [...selectedClassIds]
      };
      if (shouldFetchStudents && selectedClassIds.length > 0 && studentsCategory) {
        fetchRequestId.current += 1;
        const localRequestId = fetchRequestId.current;
        try {
          const students = await performStudentFetch(
            selectedSchoolIds,
            selectedSchoolYearIds,
            selectedClassIds,
            localRequestId
          );
          if (students === null) {
            return;
          }
          handleSuccessfulFetch(students, updatedCategories, localRequestId);
        } catch (error) {
          handleFetchError(error, updatedCategories, localRequestId);
        }
      } else if (shouldFetchStudents && studentsCategory) {
        fetchRequestId.current += 1;
        const finalCategories = clearStudentsFromCategories(updatedCategories);
        setCategories(finalCategories);
      } else {
        setCategories(updatedCategories);
      }
    },
    [
      apiClient,
      customFetchStudents,
      setCategories,
      performStudentFetch,
      handleSuccessfulFetch,
      handleFetchError
    ]
  );
  return {
    handleCategoriesChange
  };
}

// src/hooks/useSendActivity.ts
function toISODateTime(date, time) {
  return (0, import_dayjs.default)(`${date}T${time}`).toISOString();
}
function useSendActivity(config) {
  const { api, onSuccess, onError } = config;
  const [isOpen, setIsOpen] = (0, import_react2.useState)(false);
  const [selectedModel, setSelectedModel] = (0, import_react2.useState)(
    null
  );
  const [categories, setCategories] = (0, import_react2.useState)([]);
  const [isLoading, setIsLoading] = (0, import_react2.useState)(false);
  const [isCategoriesLoading, setIsCategoriesLoading] = (0, import_react2.useState)(false);
  const categoriesLoadedRef = (0, import_react2.useRef)(false);
  const initialData = (0, import_react2.useMemo)(() => {
    if (!selectedModel) return void 0;
    return {
      title: selectedModel.title
    };
  }, [selectedModel]);
  const loadCategories = (0, import_react2.useCallback)(async () => {
    if (categoriesLoadedRef.current) return;
    setIsCategoriesLoading(true);
    try {
      const categoryConfig = await loadCategoriesData(api, []);
      setCategories(categoryConfig);
      categoriesLoadedRef.current = true;
    } catch (error) {
      console.error("Error loading categories:", error);
      onError?.("Erro ao carregar destinat\xE1rios");
    } finally {
      setIsCategoriesLoading(false);
    }
  }, [api, onError]);
  const openModal = (0, import_react2.useCallback)(
    (model) => {
      setSelectedModel(model);
      setIsOpen(true);
      void loadCategories();
    },
    [loadCategories]
  );
  const closeModal = (0, import_react2.useCallback)(() => {
    setIsOpen(false);
    setSelectedModel(null);
  }, []);
  const { handleCategoriesChange: onCategoriesChange } = useDynamicStudentFetching(setCategories, { apiClient: api });
  const handleSubmit = (0, import_react2.useCallback)(
    async (data) => {
      if (!selectedModel) return;
      setIsLoading(true);
      try {
        let questionIds = null;
        try {
          const response = await api.get(`/activity-drafts/${selectedModel.id}`);
          questionIds = response.data.data.selectedQuestions?.map((q) => q.id) || null;
        } catch {
          questionIds = null;
        }
        if (!questionIds || questionIds.length === 0) {
          throw new Error("N\xE3o foi poss\xEDvel obter quest\xF5es do modelo");
        }
        const createResponse = await api.post(
          "/activities",
          {
            title: data.title,
            subjectId: selectedModel.subjectId,
            questionIds,
            subtype: data.subtype,
            isDigital: data.subtype === "PROVA" /* PROVA */ ? data.mode !== "PRESENCIAL" /* PRESENCIAL */ : true,
            notification: data.notification,
            startDate: toISODateTime(data.startDate, data.startTime),
            finalDate: toISODateTime(data.finalDate, data.finalTime),
            canRetry: data.canRetry
          }
        );
        await api.post("/activities/send-to-students", {
          activityId: createResponse.data.data.id,
          students: data.students
        });
        onSuccess?.(`Atividade enviada para ${data.students.length} aluno(s)`);
        closeModal();
      } catch (error) {
        console.error("Error sending activity:", error);
        onError?.("Erro ao enviar atividade");
      } finally {
        setIsLoading(false);
      }
    },
    [selectedModel, api, onSuccess, onError, closeModal]
  );
  return {
    isOpen,
    openModal,
    closeModal,
    selectedModel,
    initialData,
    categories,
    onCategoriesChange,
    isLoading,
    isCategoriesLoading,
    handleSubmit
  };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  useSendActivity
});
//# sourceMappingURL=index.js.map