// API 服务，统一处理错误和降级方案

export interface ApiResponse {
    success: boolean;
    message: string;
    data?: any;
}

export interface EmailSubmissionData {
    email: string;
    name?: string;
    industry?: string;
    source?: string;
}

class ApiService {
    // 可选：用于未来扩展的 API 基础 URL
    // private baseUrl: string;

    constructor() {
        // 从环境变量或默认值获取API基础URL（预留扩展用）
        // this.baseUrl = import.meta.env.VITE_API_URL || '';
    }

    /**
     * 发送欢迎邮件
     * 如果API不可用，提供降级方案
     */
    async sendWelcomeEmail(data: EmailSubmissionData): Promise<ApiResponse> {
        try {
            // 尝试调用真实API
            const response = await fetch('/api/send-welcome-email', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data),
            });

            // 如果响应不存在，可能是CORS或网络错误
            if (!response) {
                throw new Error('Network error: Unable to connect to server');
            }

            const result = await response.json();

            // 检查响应是否成功
            if (!response.ok || !result.success) {
                throw new Error(result.message || `HTTP ${response.status}: ${response.statusText}`);
            }

            return result;
        } catch (error) {
            console.warn('API call failed, falling back to local handling:', error);

            // 降级方案：本地处理和存储
            return this.handleEmailSubmissionFallback(data, error);
        }
    }

    /**
     * 邮件提交的降级方案
     */
    private handleEmailSubmissionFallback(data: EmailSubmissionData, originalError: any): ApiResponse {
        try {
            // 存储到localStorage作为备份
            const submissions = JSON.parse(localStorage.getItem('email_submissions') || '[]');
            submissions.push({
                ...data,
                timestamp: new Date().toISOString(),
                status: 'pending' // 标记为待发送
            });
            localStorage.setItem('email_submissions', JSON.stringify(submissions));

            // 创建mailto链接作为最后的降级方案
            const subject = encodeURIComponent(`CCDW Inquiry - ${data.source || 'Website'}`);
            const body = encodeURIComponent(
                `Email: ${data.email}\n` +
                `Name: ${data.name || 'Not provided'}\n` +
                `Industry: ${data.industry || 'Not specified'}\n` +
                `Source: ${data.source || 'Website'}\n` +
                `Time: ${new Date().toLocaleString()}`
            );
            const mailtoLink = `mailto:contact@ccdw.xyz?subject=${subject}&body=${body}`;

            // 提供用户友好的降级消息
            const isDevelopment = import.meta.env.DEV;
            const fallbackMessage = isDevelopment
                ? `开发模式：邮件已记录到本地存储。\n\n详细信息：${JSON.stringify(data, null, 2)}`
                : `感谢您的订阅！我们已记录您的信息，将尽快与您联系。\n\n如果需要立即联系我们，请发送邮件至：contact@ccdw.xyz`;

            return {
                success: true,
                message: fallbackMessage,
                data: {
                    mailtoLink,
                    storedLocally: true,
                    originalError: originalError?.message || 'Unknown error'
                }
            };
        } catch (fallbackError) {
            // 如果连降级方案都失败了
            console.error('Fallback also failed:', fallbackError);
            return {
                success: false,
                message: '抱歉，服务暂时不可用。请稍后重试或直接发送邮件至 contact@ccdw.xyz'
            };
        }
    }

    /**
     * 尝试重新发送本地存储的待发送邮件
     */
    async retryPendingSubmissions(): Promise<ApiResponse[]> {
        const submissions = JSON.parse(localStorage.getItem('email_submissions') || '[]');
        const pendingSubmissions = submissions.filter((sub: any) => sub.status === 'pending');

        if (pendingSubmissions.length === 0) {
            return [{ success: true, message: 'No pending submissions' }];
        }

        const results: ApiResponse[] = [];

        for (const submission of pendingSubmissions) {
            try {
                const result = await this.sendWelcomeEmail(submission);
                results.push(result);

                // 如果成功，更新状态
                if (result.success) {
                    submission.status = 'sent';
                    submission.sentAt = new Date().toISOString();
                }
            } catch (error) {
                results.push({
                    success: false,
                    message: `Failed to resend: ${error}`
                });
            }
        }

        // 更新localStorage
        localStorage.setItem('email_submissions', JSON.stringify(submissions));

        return results;
    }

    /**
     * 获取本地存储的提交历史
     */
    getLocalSubmissions(): any[] {
        return JSON.parse(localStorage.getItem('email_submissions') || '[]');
    }

    /**
     * 清除本地存储的提交数据
     */
    clearLocalSubmissions(): void {
        localStorage.removeItem('email_submissions');
    }
}

// 导出单例实例
export const apiService = new ApiService();

// 导出类型
export default apiService;