// 文本模板API接口
const apiRequest = async (endpoint, options = {}) => {
    const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000';
    const url = `${baseURL}${endpoint}`;
    const defaultOptions = {
        headers: {
            'Content-Type': 'application/json',
        },
        ...options,
    };

    // 注意：文本模板API目前不需要认证
    // 如果需要认证，可以在这里添加token

    try {
        const response = await fetch(url, defaultOptions);

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

        return await response.json();
    } catch (error) {
        console.error('API request failed:', error);
        throw error;
    }
}

// 文本模板API类
export class TextTemplateAPI {
    constructor() {
        this.baseURL = '/api/v1';
    }

    // 创建文本模板
    async createTextTemplate(userId, textType, textName, textLabel, textContent) {
        const formData = new FormData();
        formData.append('text_type', textType);
        formData.append('text_name', textName);
        formData.append('text_label', textLabel);
        formData.append('text_content', textContent);

        const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000';
        const url = `${baseURL}${this.baseURL}/users/${userId}/templates`;

        console.log(`创建文本模板请求详情:`, {
            url,
            userId,
            textType,
            textName,
            textLabel,
            textContent,
        })

        const headers = {};
        // 注意：文本模板API目前不需要认证
        // 如果需要认证，可以在这里添加token

        try {
            const response = await fetch(url, {
                method: 'POST',
                headers,
                body: formData,
            });

            console.log('创建文本模板响应状态:', response.status, response.statusText);

            if (!response.ok) {
                const errorText = await response.text();
                console.error('创建文本模板失败详情：', errorText);
                throw new Error(`创建文本模板失败: ${response.status} - ${errorText}`);
            }
            const result = await response.json();
            console.log('创建文本模板成功结果:', result);
            return result;

        } catch (error) {
            console.error('创建文本模板请求异常:', error);
            throw error;
        }
    }

    // 获取文本模板列表
    async getTextTemplates(userId, textType = null, page = 1, pageSize = 20) {
        let url = `${this.baseURL}/users/${userId}/templates?page=${page}&page_size=${pageSize}`;
        if (textType) {
            url += `&text_type=${textType}`;
        }

        return await apiRequest(url);
    }

    // 更新文本模板（部分字段可选）
    async updateTextTemplate(userId, textId, { textType, textName, textLabel, textContent } = {}) {
        const formData = new FormData();
        if (textType !== undefined) formData.append('text_type', textType);
        if (textName !== undefined) formData.append('text_name', textName);
        if (textLabel !== undefined) formData.append('text_label', textLabel);
        if (textContent !== undefined) formData.append('text_content', textContent);

        const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000';
        const url = `${baseURL}${this.baseURL}/users/${userId}/templates/${textId}`;

        const response = await fetch(url, {
            method: 'PUT',
            body: formData,
        });
        if (!response.ok) {
            const errorText = await response.text();
            throw new Error(`更新文本模板失败: ${response.status} - ${errorText}`);
        }
        return await response.json();
    }

    // 删除文本模板
    async deleteTextTemplate(userId, textId) {
        return await apiRequest(`${this.baseURL}/users/${userId}/templates/${textId}`, {
            method: 'DELETE',
        });
    }
}

// 创建单例实例
export const textTemplateAPI = new TextTemplateAPI();