import axios, { AxiosError, AxiosInstance, AxiosResponse } from 'axios';

export class CanvasClient {
    private axiosInstance: AxiosInstance;
    private accessToken: string;

    constructor(accessToken: string = process.env.CANVAS_API_TOKEN || '') {
        this.accessToken = accessToken;
        this.axiosInstance = axios.create({
            baseURL: 'https://your-canvas-domain.com/api/v1/',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${this.accessToken}`,
            },
        });
    }

    async get<T>(endpoint: string, params?: Record<string, any>): Promise<T> {
        try {
            const response: AxiosResponse<T> = await this.axiosInstance.get(endpoint, {
                params,
            });
            return response.data;
        } catch (error) {
            this.handleError(error);
        }
    }

    async post<T>(endpoint: string, data?: object): Promise<T> {
        try {
            const response: AxiosResponse<T> = await this.axiosInstance.post(endpoint, data);
            return response.data;
        } catch (error) {
            this.handleError(error);
        }
    }

    async put<T>(endpoint: string, data?: object): Promise<T> {
        try {
            const response: AxiosResponse<T> = await this.axiosInstance.put(endpoint, data);
            return response.data;
        } catch (error) {
            this.handleError(error);
        }
    }

    async delete<T>(endpoint: string, data?: object): Promise<T> {
        try {
            const response: AxiosResponse<T> = await this.axiosInstance.delete(endpoint, {
                data,
            });
            return response.data;
        } catch (error) {
            this.handleError(error);
        }
    }

    private handleError(error: unknown): never {
        const axiosError = error as AxiosError;
        if (axiosError.response) {
            throw axiosError.response.data;
        } else {
            throw new Error('Network error or no response from server');
        }
    }
}
