import pb from '../lib/pb'; import { useAuthStore } from '../store/authStore'; export function useMicroLearningCompletions() { const { user } = useAuthStore?.() || { user: pb.authStore.model }; // Note: user in PB context for team_members usually matches user_id or team_member_id. // We need the team_member record. If the frontend is currently storing it in authStore, we can get it. const recordCompletion = async ({ microLearningId, topicId, type, sessionWeek }) => { try { // Find the team_member record for the current user let teamMemberId = user?.id; // If user is just the auth user, we might need to query the team_members collection // but in many setups, the auth user is the team_member or there's a 1-to-1. // Let's ensure we fetch team_member_id properly if needed. const teamMemberRec = await pb.collection('team_members').getFirstListItem(`user_id = "${user.id}"`); if (!teamMemberRec) { throw new Error("Team member record not found for user."); } const record = await pb.collection('micro_learning_completions').create({ team_member_id: teamMemberRec.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 teamMemberRec = await pb.collection('team_members').getFirstListItem(`user_id = "${pb.authStore.model.id}"`); if (!teamMemberRec) return []; const records = await pb.collection('micro_learning_completions').getFullList({ filter: `team_member_id = "${teamMemberRec.id}" && session_week = ${sessionWeek}` }); return records; } catch (err) { console.error("Error fetching session completions:", err); return []; } }; return { recordCompletion, getSessionCompletions }; }