// api_client.js
const BASE_URL = 'https://evie.askeveai.com/api/api/v1';

class EveAIApiClient {
    constructor(z, bundle) {
        this.z = z;
        this.bundle = bundle;
    }

    async ensure_valid_token() {
        const currentTime = Math.floor(Date.now() / 1000);  // Current time in seconds
        const token = this.bundle.authData.access_token;
        const tokenExpiry = this.bundle.authData.token_expiry;
        // Check if token is expired or will expire in next 30 seconds
        if (!token || !tokenExpiry || currentTime + 30 >= tokenExpiry) {
            this.z.console.log('Token missing or expiring soon, requesting new token...');

            const response = await this.z.request({
                url: `${BASE_URL}/auth/token`,
                method: 'POST',
                body: {
                    tenant_id: this.bundle.authData.tenant_id,
                    api_key: this.bundle.authData.api_key,
                },
            });

            if (response.status !== 200) {
                throw new Error(`Failed to get access token: ${response.status}`);
            }

            const data = response.json;

            // Update the bundle's authData
            this.bundle.authData.access_token = data.access_token;
            this.bundle.authData.token_expiry = currentTime + data.expires_in;

            this.z.console.log('New token obtained:', {
                token_prefix: data.access_token.substring(0, 10) + '...',
                expires_in: data.expires_in,
                expiry_time: this.bundle.authData.token_expiry
            });

            return data.access_token;
        }

        this.z.console.log('Using existing valid token');
        return token;
    }

    async make_request(method, endpoint, data = null) {
        try {
            // Ensure we have a valid token
            const token = await this.ensure_valid_token();

            this.z.console.log('Making request:', {
                method,
                endpoint,
                token_prefix: token.substring(0, 10) + '...'
            });

            const requestConfig = {
                url: `${BASE_URL}${endpoint}`,
                method,
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json',
                },
            };

            if (data) {
                requestConfig.body = data;
            }

            const response = await this.z.request(requestConfig);

            this.z.console.log('Response received:', {
                status: response.status,
                data: response.json
            });

            return response.json;

        } catch (error) {
            this.z.console.error('Request failed:', {
                error: error.message,
                response: error.response
            });
            throw error;
        }
    }
}

module.exports = EveAIApiClient;