import { auth } from './auth.js';

export const BASE_URL = '/api';

/**
 * API Wrapper for SaaS Meta Backend
 */
export const api = {
    // Current User State
    getCurrentUserId() {
        return auth.getUserId() || '';
    },

    async request(path, options = {}) {
        const response = await fetch(`${BASE_URL}${path}`, options);
        if (!response.ok) {
            const error = await response.json().catch(() => ({ message: 'Network error' }));
            throw { status: response.status, ...error };
        }
        return response.json();
    },

    // 1. Users
    async getAllUsers() {
        return this.request('/users');
    },

    async login(email) {
        return this.request('/users/login', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ email })
        });
    },

    // 2. Meta Ads
    async connectMeta(data) {
        const userId = this.getCurrentUserId();
        return this.request('/meta/connect', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ ...data, userId }) // adAccountId inside data
        });
    },

    async getConnectedAccounts() {
        const userId = this.getCurrentUserId();
        return this.request('/meta/accounts', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ userId })
        });
    },

    async getInsights(params = {}) {
        const userId = this.getCurrentUserId();
        return this.request('/meta/insights', {
            method: 'POST',
            headers: { 
                'Content-Type': 'application/json',
                'x-user-id': userId
            },
            body: JSON.stringify(params)
        });
    },

    // 3. AI Analysis
    async analyzeVisual(imageUrl, copy, metrics = null, campaignId = null) {
        const userId = this.getCurrentUserId();
        return this.request('/analyze/visual', {
            method: 'POST',
            headers: { 
                'Content-Type': 'application/json',
                'x-user-id': userId
            },
            body: JSON.stringify({ imageUrl, adCopy: copy, metrics, campaignId })
        });
    },

    // 4. Sample Data for Demo Mode
    async getSampleData(params = {}) {
        const userId = this.getCurrentUserId();
        return this.request('/analyze/sample', {
            method: 'POST',
            headers: { 
                'Content-Type': 'application/json',
                'x-user-id': userId
            },
            body: JSON.stringify(params) 
        });
    },

    // 5. Automation Rules
    async getRules() {
        const userId = this.getCurrentUserId();
        return this.request(`/automation/rules/${userId}`);
    },

    async createRule(ruleData) {
        const userId = this.getCurrentUserId();
        return this.request('/automation/rules', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ ...ruleData, userId })
        });
    },

    async deleteRule(ruleId) {
        return this.request(`/automation/rules/${ruleId}`, {
            method: 'DELETE'
        });
    }
};
