import axios from 'axios';
import { logger } from '../utils/logger';

// Get API base URL from runtime config (window.env) or build-time config
// IMPORTANT: Call this function at REQUEST TIME, not at module load time,
// to ensure window.env is populated by env-config.js
const getApiBaseUrl = (): string => {
  // Check window.env first (runtime config from env.sh)
  if (typeof window !== 'undefined' && window.env?.API_BASE_URL) {
    return window.env.API_BASE_URL;
  }

  // Fall back to build-time env or production default
  // Next.js requires direct static reference to NEXT_PUBLIC_ variables
  return process.env.NEXT_PUBLIC_API_BASE_URL || 'https://puffinoffset.com/api';
};

export interface ContactEmailData {
  name: string;
  email: string;
  phone?: string;
  company?: string;
  message: string;
}

export interface ReceiptEmailData {
  customerEmail: string;
  orderDetails: {
    tons: number;
    portfolioId: number;
    baseAmount: number;
    processingFee: number;
    totalAmount: number;
    orderId: string;
    stripeSessionId: string;
  };
}

export interface AdminNotificationData {
  orderDetails: {
    tons: number;
    portfolioId: number;
    totalAmount: number;
    orderId: string;
  };
  customerEmail: string;
}

export interface EmailResponse {
  success: boolean;
  messageId: string;
  message: string;
  skipped?: boolean;
}

/**
 * Send contact form email to admin
 * @param data Contact form data
 * @returns Email response with message ID
 */
export async function sendContactEmail(data: ContactEmailData): Promise<EmailResponse> {
  try {
    const apiBaseUrl = getApiBaseUrl();
    logger.info('Sending contact form email:', { name: data.name, email: data.email });
    logger.info('Using API base URL:', apiBaseUrl);

    const response = await axios.post<EmailResponse>(
      `${apiBaseUrl}/api/email/contact`,
      data
    );

    logger.info('Contact email sent successfully:', response.data.messageId);
    return response.data;
  } catch (error) {
    if (axios.isAxiosError(error)) {
      logger.error('Contact email failed:', error.response?.data || error.message);
      throw new Error(error.response?.data?.error || 'Failed to send contact form');
    }
    throw error;
  }
}

/**
 * Send receipt email to customer
 * @param data Receipt email data with order details
 * @returns Email response with message ID
 */
export async function sendReceiptEmail(data: ReceiptEmailData): Promise<EmailResponse> {
  try {
    const apiBaseUrl = getApiBaseUrl();
    logger.info('Sending receipt email to:', data.customerEmail);
    logger.info('Order ID:', data.orderDetails.orderId);

    const response = await axios.post<EmailResponse>(
      `${apiBaseUrl}/api/email/receipt`,
      data
    );

    logger.info('Receipt email sent successfully:', response.data.messageId);
    return response.data;
  } catch (error) {
    if (axios.isAxiosError(error)) {
      logger.error('Receipt email failed:', error.response?.data || error.message);
      throw new Error(error.response?.data?.error || 'Failed to send receipt email');
    }
    throw error;
  }
}

/**
 * Send admin notification for new order
 * @param data Admin notification data
 * @returns Email response with message ID
 */
export async function sendAdminNotification(
  data: AdminNotificationData
): Promise<EmailResponse> {
  try {
    const apiBaseUrl = getApiBaseUrl();
    logger.info('Sending admin notification for order:', data.orderDetails.orderId);

    const response = await axios.post<EmailResponse>(
      `${apiBaseUrl}/api/email/admin-notify`,
      data
    );

    if (response.data.skipped) {
      logger.info('Admin notification skipped (disabled in config)');
    } else {
      logger.info('Admin notification sent successfully:', response.data.messageId);
    }
    return response.data;
  } catch (error) {
    if (axios.isAxiosError(error)) {
      logger.error('Admin notification failed:', error.response?.data || error.message);
      // Don't throw - admin notifications should not block user experience
      logger.warn('Admin notification failure is non-fatal, continuing...');
      return {
        success: false,
        messageId: '',
        message: 'Admin notification failed (non-fatal)',
      };
    }
    throw error;
  }
}
