import { ref } from "vue";

export const useNotificationDelivery = () => {
  const isLoading = ref(false);
  const error = ref(null);
  const deliveryStats = ref(null);
  const emailConfig = ref(null);
  const pushConfig = ref(null);
  const smsConfig = ref(null);
  const deliverySettings = ref(null);
  const deliveryProviders = ref([]);
  const deliveryMetrics = ref({
    sent: 0,
    delivered: 0,
    failed: 0,
    pending: 0
  });
  
  // Reset error state
  const resetError = () => {
    error.value = null;
  };

  // Fetch delivery statistics
  const fetchDeliveryStats = async () => {
    isLoading.value = true;
    error.value = null;

    try {
      const response = await $fetch("/api/notifications/delivery/stats");
      
      if (response.success) {
        deliveryStats.value = response.data;
        
        // Update metrics from stats
        deliveryMetrics.value = {
          sent: response.data.totalSent || 0,
          delivered: response.data.totalDelivered || 0,
          failed: response.data.totalFailed || 0,
          pending: response.data.totalPending || 0
        };
        
        return response.data;
      } else {
        throw new Error(response.message || "Failed to fetch delivery stats");
      }
    } catch (err) {
      error.value = err.data?.message || err.message || "Failed to fetch delivery stats";
      throw error.value;
    } finally {
      isLoading.value = false;
    }
  };

  // Fetch email configuration
  const fetchEmailConfig = async () => {
    isLoading.value = true;
    error.value = null;
    
    try {
      const response = await $fetch("/api/notifications/delivery/email-config");
      
      if (response.success) {
        emailConfig.value = response.data;
        return response.data;
      } else {
        throw new Error(response.message || "Failed to fetch email configuration");
      }
    } catch (err) {
      error.value = err.data?.message || err.message || "Failed to fetch email configuration";
      throw error.value;
    } finally {
      isLoading.value = false;
    }
  };

  // Fetch push notification configuration
  const fetchPushConfig = async () => {
    isLoading.value = true;
    error.value = null;
    
    try {
      const response = await $fetch("/api/notifications/delivery/push-config");
      
      if (response.success) {
        pushConfig.value = response.data;
        return response.data;
      } else {
        throw new Error(response.message || "Failed to fetch push configuration");
      }
    } catch (err) {
      error.value = err.data?.message || err.message || "Failed to fetch push configuration";
      throw error.value;
    } finally {
      isLoading.value = false;
    }
  };

  // Fetch SMS configuration
  const fetchSmsConfig = async () => {
    isLoading.value = true;
    error.value = null;
    
    try {
      const response = await $fetch("/api/notifications/delivery/sms-config");
      
      if (response.success) {
        smsConfig.value = response.data;
        return response.data;
      } else {
        throw new Error(response.message || "Failed to fetch SMS configuration");
      }
    } catch (err) {
      error.value = err.data?.message || err.message || "Failed to fetch SMS configuration";
      throw error.value;
    } finally {
      isLoading.value = false;
    }
  };

  // Fetch delivery settings
  const fetchDeliverySettings = async () => {
    isLoading.value = true;
    error.value = null;
    
    try {
      const response = await $fetch("/api/notifications/delivery/settings");
      
      if (response.success) {
        deliverySettings.value = response.data;
        return response.data;
      } else {
        throw new Error(response.message || "Failed to fetch delivery settings");
      }
    } catch (err) {
      error.value = err.data?.message || err.message || "Failed to fetch delivery settings";
      throw error.value;
    } finally {
      isLoading.value = false;
    }
  };
  
  // Fetch all delivery providers
  const fetchDeliveryProviders = async () => {
    isLoading.value = true;
    error.value = null;
    
    try {
      const response = await $fetch("/api/notifications/delivery/providers");
      
      if (response.success) {
        deliveryProviders.value = response.data;
        return response.data;
      } else {
        throw new Error(response.message || "Failed to fetch delivery providers");
      }
    } catch (err) {
      error.value = err.data?.message || err.message || "Failed to fetch delivery providers";
      throw error.value;
    } finally {
      isLoading.value = false;
    }
  };

  // Fetch delivery performance metrics
  const fetchDeliveryPerformance = async (period = 'last_30_days') => {
    isLoading.value = true;
    error.value = null;
    
    try {
      const response = await $fetch(`/api/notifications/delivery/performance?period=${period}`);
      
      if (response.success) {
        return response.data;
      } else {
        throw new Error(response.message || "Failed to fetch delivery performance");
      }
    } catch (err) {
      error.value = err.data?.message || err.message || "Failed to fetch delivery performance";
      throw error.value;
    } finally {
      isLoading.value = false;
    }
  };
  
  // Test delivery configuration
  const testDeliveryConfig = async (channel, config) => {
    isLoading.value = true;
    error.value = null;
    
    try {
      const response = await $fetch("/api/notifications/delivery/test", {
        method: "POST",
        body: {
          channel,
          config
        }
      });
      
      if (response.success) {
        return {
          success: true,
          message: response.message || "Test successful"
        };
      } else {
        throw new Error(response.message || `Failed to test ${channel} configuration`);
      }
    } catch (err) {
      error.value = err.data?.message || err.message || `Failed to test ${channel} configuration`;
      throw error.value;
    } finally {
      isLoading.value = false;
    }
  };

  // Update email configuration
  const updateEmailConfig = async (config) => {
    isLoading.value = true;
    error.value = null;
    
    try {
      const response = await $fetch("/api/notifications/delivery/email-config", {
        method: "PUT",
        body: config,
      });
      
      if (response.success) {
        // Update local state
        emailConfig.value = response.data;
        return response.data;
      } else {
        throw new Error(response.message || "Failed to update email configuration");
      }
    } catch (err) {
      error.value = err.data?.message || err.message || "Failed to update email configuration";
      throw error.value;
    } finally {
      isLoading.value = false;
    }
  };

  // Update push notification configuration
  const updatePushConfig = async (config) => {
    isLoading.value = true;
    error.value = null;
    
    try {
      const response = await $fetch("/api/notifications/delivery/push-config", {
        method: "PUT",
        body: config,
      });
      
      if (response.success) {
        // Update local state
        pushConfig.value = response.data;
        return response.data;
      } else {
        throw new Error(response.message || "Failed to update push configuration");
      }
    } catch (err) {
      error.value = err.data?.message || err.message || "Failed to update push configuration";
      throw error.value;
    } finally {
      isLoading.value = false;
    }
  };

  // Update SMS configuration
  const updateSmsConfig = async (config) => {
    isLoading.value = true;
    error.value = null;
    
    try {
      const response = await $fetch("/api/notifications/delivery/sms-config", {
        method: "PUT",
        body: config,
      });
      
      if (response.success) {
        // Update local state
        smsConfig.value = response.data;
        return response.data;
      } else {
        throw new Error(response.message || "Failed to update SMS configuration");
      }
    } catch (err) {
      error.value = err.data?.message || err.message || "Failed to update SMS configuration";
      throw error.value;
    } finally {
      isLoading.value = false;
    }
  };

  // Update delivery settings
  const updateDeliverySettings = async (settings) => {
    isLoading.value = true;
    error.value = null;
    
    try {
      const response = await $fetch("/api/notifications/delivery/settings", {
        method: "PUT",
        body: settings,
      });
      
      if (response.success) {
        // Update local state
        deliverySettings.value = response.data;
        return response.data;
      } else {
        throw new Error(response.message || "Failed to update delivery settings");
      }
    } catch (err) {
      error.value = err.data?.message || err.message || "Failed to update delivery settings";
      throw error.value;
    } finally {
      isLoading.value = false;
    }
  };
  
  // Retry failed deliveries
  const retryFailedDeliveries = async (notificationId = null) => {
    isLoading.value = true;
    error.value = null;
    
    try {
      const endpoint = notificationId 
        ? `/api/notifications/delivery/retry/${notificationId}` 
        : "/api/notifications/delivery/retry";
        
      const response = await $fetch(endpoint, {
        method: "POST"
      });
      
      if (response.success) {
        return {
          success: true,
          message: response.message || "Retry initiated successfully",
          data: response.data
        };
      } else {
        throw new Error(response.message || "Failed to retry deliveries");
      }
    } catch (err) {
      error.value = err.data?.message || err.message || "Failed to retry deliveries";
      throw error.value;
    } finally {
      isLoading.value = false;
    }
  };
  
  // Fetch delivery logs
  const fetchDeliveryLogs = async (params = {}) => {
    isLoading.value = true;
    error.value = null;
    
    try {
      const queryString = new URLSearchParams();
      
      if (params.page) queryString.append("page", params.page);
      if (params.limit) queryString.append("limit", params.limit);
      if (params.status) queryString.append("status", params.status);
      if (params.channel) queryString.append("channel", params.channel);
      if (params.notificationId) queryString.append("notificationId", params.notificationId);
      if (params.startDate) queryString.append("startDate", params.startDate);
      if (params.endDate) queryString.append("endDate", params.endDate);
      
      const response = await $fetch(`/api/notifications/delivery/logs?${queryString.toString()}`);
      
      if (response.success) {
        return response.data;
      } else {
        throw new Error(response.message || "Failed to fetch delivery logs");
      }
    } catch (err) {
      error.value = err.data?.message || err.message || "Failed to fetch delivery logs";
      throw error.value;
    } finally {
      isLoading.value = false;
    }
  };

  return {
    // State
    isLoading,
    error,
    deliveryStats,
    emailConfig,
    pushConfig,
    smsConfig,
    deliverySettings,
    deliveryProviders,
    deliveryMetrics,
    
    // Methods
    resetError,
    fetchDeliveryStats,
    fetchEmailConfig,
    fetchPushConfig,
    fetchSmsConfig,
    fetchDeliverySettings,
    fetchDeliveryProviders,
    fetchDeliveryPerformance,
    fetchDeliveryLogs,
    testDeliveryConfig,
    updateEmailConfig,
    updatePushConfig,
    updateSmsConfig,
    updateDeliverySettings,
    retryFailedDeliveries
  };
}; 