/**
 * Grid Stabilizer - Home Assistant Client
 */
class HAClient {
    constructor(url, token) {
        this.url = url;
        this.token = token;
    }

    async callService(domain, service, entityId) {
        if (!this.token || this.token === 'YOUR_HOME_ASSISTANT_LONG_LIVED_ACCESS_TOKEN') {
            const msg = 'HAClient: No valid token provided. Skipping HA call.';
            console.warn(msg);
            throw new Error(msg);
        }

        if (this.url.includes('homeassistant.local') && window.location.protocol === 'https:') {
            const msg = 'HAClient: Cannot call insecure local HA from HTTPS (Mixed Content). Use IP or SSL.';
            console.warn(msg);
            throw new Error(msg);
        }

        try {
            console.log(`HAClient: Calling service ${domain}.${service} on ${entityId}...`);
            const response = await fetch(`${this.url}services/${domain}/${service}`, {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${this.token}`,
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ entity_id: entityId }),
            });

            if (!response.ok) {
                const errorText = await response.text();
                throw new Error(`HA API Error (${response.status} ${response.statusText}): ${errorText}`);
            }

            console.log(`HAClient: Successfully triggered ${domain}.${service} for ${entityId}`);
            return true;
        } catch (error) {
            console.error('HAClient: Error calling service:', error);
            // Re-throw or handle so UI can show it
            throw error;
        }
    }

    async triggerScene(sceneId) {
        return await this.callService('scene', 'turn_on', sceneId);
    }

    async triggerWebhook(url) {
        if (!url) return false;
        try {
            console.log(`HAClient: Triggering Webhook ${url}...`);
            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ action: 'trigger', source: 'grid_stabilizer' }),
            });

            if (!response.ok) {
                throw new Error(`Webhook Error: ${response.status} ${response.statusText}`);
            }

            console.log(`HAClient: Successfully triggered Webhook ${url}`);
            return true;
        } catch (error) {
            console.error('HAClient: Error triggering webhook:', error);
            throw error;
        }
    }
}

export default HAClient;
