import { useState, useEffect, useCallback } from 'react';
import { ListCoursesResponse, PublicCourse } from '@/types/courses';
interface UseCoursesOptions {
page?: number;
limit?: number;
search?: string;
categoryId?: string;
sortBy?: 'name' | 'students' | 'modules';
}
interface UseCoursesResult {
courses: PublicCourse[];
pagination: { page: number; limit: number; total: number; totalPages: number } | null;
loading: boolean;
error: string | null;
refetch: () => void;
}
export function useCourses(options: UseCoursesOptions = {}): UseCoursesResult {
const { page = 1, limit = 12, search, categoryId, sortBy } = options;
const [courses, setCourses] = useState<PublicCourse[]>([]);
const [pagination, setPagination] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const fetchCourses = useCallback(async () => {
try {
setLoading(true);
setError(null);
const params = new URLSearchParams();
params.set('page', String(page));
params.set('limit', String(limit));
if (search) params.set('search', search);
if (categoryId) params.set('categoryId', categoryId);
if (sortBy) params.set('sortBy', sortBy);
// For frontend use, include credentials for session cookie
const res = await fetch(`/api/courses?${params}`, {
credentials: 'include',
headers: {
'x-api-key': '...' // optional: use when calling from server-side
}
});
if (!res.ok) {
if (res.status === 401) throw new Error('Unauthorized. Provide a valid API key or log in.');
if (res.status === 429) throw new Error('Rate limited. Wait before retrying.');
throw new Error(`Server returned ${res.status}`);
}
const data: ListCoursesResponse = await res.json();
if (!data.success) throw new Error('Failed to load courses.');
setCourses(data.courses);
setPagination(data.pagination ?? null);
} catch (err: any) {
setError(err.message || 'An unknown error occurred.');
} finally {
setLoading(false);
}
}, [page, limit, search, categoryId, sortBy]);
useEffect(() => { fetchCourses(); }, [fetchCourses]);
return { courses, pagination, loading, error, refetch: fetchCourses };
}