import { pb } from '../lib/pb';
import { useApp } from '../store/AppContext';

export function useMicroLearningCompletions() {
  const { state } = useApp();

  const recordCompletion = async ({ microLearningId, topicId, type, sessionWeek }) => {
    try {
      const user = state.currentUser;
      if (!user) throw new Error("No authenticated user");

      const record = await pb.collection('micro_learning_completions').create({
        team_member_id: user.id,
        micro_learning_id: microLearningId,
        topic_id: topicId,
        type: type,
        session_week: sessionWeek
      });
      return record;
    } catch (err) {
      console.error("Error recording completion:", err);
      return null;
    }
  };

  const getSessionCompletions = async (sessionWeek) => {
    try {
      const user = state.currentUser;
      if (!user) return [];

      const records = await pb.collection('micro_learning_completions').getFullList({
        filter: `team_member_id = "${user.id}" && session_week = ${sessionWeek}`
      });
      return records;
    } catch (err) {
      console.error("Error fetching session completions:", err);
      return [];
    }
  };

  return { recordCompletion, getSessionCompletions };
}
