import { api } from './api';

interface CanvasApiConfig {
    baseUrl: string;
    accessToken: string;
    courseId?: number;
}

const DEFAULT_CANVAS_CONFIG: CanvasApiConfig = {
    baseUrl: import.meta.env.VITE_CANVAS_API_BASE_URL || 'https://canvas.instructure.com',
    accessToken: import.meta.env.VITE_CANVAS_ACCESS_TOKEN || '',
};

/**
 * Constructs a Canvas API endpoint URL with optional parameters
 */
export const constructCanvasEndpoint = (path: string, params?: Record<string, any>) => {
    const queryString = params ? `?${new URLSearchParams(params).toString()}` : '';
    return `${path}${queryString}`;
};

/**
 * Makes a request to the Canvas API
 */
export const getCanvasData = async <T = any>(
    endpoint: string,
    params?: Record<string, any>,
    config: Partial<CanvasApiConfig> = {}
): Promise<T> => {
    const finalConfig = { ...DEFAULT_CANVAS_CONFIG, ...config };
    const url = constructCanvasEndpoint(endpoint, params);

    try {
        const response = await api<T>('get', url, undefined, undefined, 'json', 60, true);
        return response.data;
    } catch (error) {
        console.error('Canvas API Error:', error);
        throw error;
    }
};

// Example usage:
// const students = await getCanvasData('/courses/123/users', { enrollment_type: ['student'] });
// const courses = await getCanvasData('/courses', { per_page: 100 });

class CanvasApi {
    private accessToken: string;
    private baseUrl: string;

    constructor(config: CanvasApiConfig) {
        this.accessToken = config.accessToken;
        this.baseUrl = config.baseUrl || DEFAULT_CANVAS_CONFIG.baseUrl;
    }

    private getHeaders() {
        return {
            Authorization: `Bearer ${this.accessToken}`,
            'Content-Type': 'application/json',
        };
    }

    async getStudents(courseId: number) {
        try {
            const response = await getCanvasData('/courses/' + courseId + '/users', {
                enrollment_type: ['student'],
                per_page: 100,
            });
            return response;
        } catch (error) {
            console.error('Error fetching students:', error);
            throw error;
        }
    }

    // Add more Canvas API methods here as needed
}

export default CanvasApi; 