import { supabase } from '@/integrations/supabase/client';
import { logNotificationCreation, logError } from '@/lib/notificationDebugUtils';

/**
 * Invokes a Supabase Edge Function safely.
 */
async function invokeEdgeFunction(functionName, options = {}) {
  try {
    const { data, error } = await supabase.functions.invoke(functionName, options);
    if (error) throw error;
    return { data, error: null };
  } catch (error) {
    console.error(`[invokeEdgeFunction] ${functionName} failed:`, error);
    return { data: null, error };
  }
}

/**
 * Creates a generic notification using the database function to bypass RLS.
 */
export async function createNotification({
  userId,
  type,
  title,
  message,
  relatedItemId = null,
  relatedItemType = null
}) {
  if (!userId) {
    console.warn('createNotification skipped: No userId provided');
    return { error: 'No user ID provided' };
  }

  try {
    const { data, error } = await supabase.rpc('create_notification', {
      p_user_id: userId,
      p_type: type,
      p_title: title,
      p_content: message,
      p_related_item_id: relatedItemId,
      p_related_item_type: relatedItemType
    });

    if (error) throw error;

    logNotificationCreation(type, userId, title);
    return { success: true, data };
  } catch (error) {
    logError('createNotification', error);
    return { success: false, error };
  }
}

/**
 * Invokes a notification-related Edge Function safely
 */
export async function sendEdgeNotification(functionName, payload) {
  if (functionName === 'send-notification') {
    if (!payload || !payload.email) {
      console.error('[sendEdgeNotification] Email is required for send-notification');
      return { 
        data: null, 
        error: new Error('Email address is required for this notification type') 
      };
    }
    
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(payload.email)) {
      console.error('[sendEdgeNotification] Invalid email format:', payload.email);
      return {
        data: null,
        error: new Error('Invalid email address format')
      };
    }
  }

  return invokeEdgeFunction(functionName, { body: payload });
}

/**
 * Specific Edge Function Wrappers
 */
export async function sendTaskNotification(taskId, action) {
  return invokeEdgeFunction('send-task-notification', { 
    body: { taskId, action } 
  });
}

export async function sendAdminNotification(type, data) {
  return invokeEdgeFunction('send-admin-notification', { 
    body: { type, data } 
  });
}

export async function sendClientNotification(clientId, type, data) {
  return invokeEdgeFunction('send-client-notification', { 
    body: { clientId, type, data } 
  });
}

/**
 * Notification Helper Functions
 */

export async function createCommentNotification(userId, itemId, itemType, commenterName) {
  return createNotification({
    userId,
    type: 'comment',
    title: 'New Comment',
    message: `${commenterName} commented on a ${itemType}.`,
    relatedItemId: itemId,
    relatedItemType: itemType
  });
}

export async function createDateRequestNotification(userId, status, date) {
    const title = status === 'approved' ? 'Date Request Approved' : (status === 'rejected' ? 'Date Request Rejected' : 'Date Request Update');
    const message = status === 'approved' 
        ? `Your request for ${date} has been approved.` 
        : (status === 'rejected' ? `Your request for ${date} has been rejected.` : `Status updated for ${date}.`);
        
    return createNotification({
        userId,
        type: 'date_request_update',
        title,
        message,
        relatedItemType: 'client_date_request'
    });
}

export async function createCalendarEventNotification(userId, action, eventTitle) {
    const title = action === 'create' ? 'New Event' : 'Event Updated';
    const message = action === 'create' 
       ? `New event "${eventTitle}" has been added to the calendar.`
       : `Event "${eventTitle}" has been updated.`;

    return createNotification({
        userId,
        type: 'calendar_event',
        title,
        message,
        relatedItemType: 'calendar_event'
    });
}

export async function createViolationNotification(userId, address, status) {
    return createNotification({
        userId,
        type: 'violation',
        title: 'Violation Update',
        message: `Violation at ${address} is now ${status}.`,
        relatedItemType: 'violation'
    });
}

export async function createCollectionNotification(userId, address, amount, status) {
    return createNotification({
        userId,
        type: 'collection',
        title: 'Collection Update',
        message: `Collection for ${address} ($${amount}) is now ${status}.`,
        relatedItemType: 'collection'
    });
}

export async function createDocumentNotification(userId, docTitle, status) {
    return createNotification({
        userId,
        type: 'document',
        title: 'Document Update',
        message: `Document "${docTitle}" is now ${status}.`,
        relatedItemType: 'document'
    });
}

export async function createStatusUpdateNotification(userId, title, action = 'create') {
    return createNotification({
        userId,
        type: 'status_update',
        title: action === 'create' ? 'New Status Update' : 'Status Update Modified',
        message: `An update regarding "${title}" has been posted.`,
        relatedItemType: 'status_update'
    });
}

export async function createARCApplicationNotification(userId, address, status) {
    return createNotification({
        userId,
        type: 'arc',
        title: 'ARC Application Update',
        message: `ARC Application for ${address} is now ${status}.`,
        relatedItemType: 'arc_application'
    });
}

export async function createOwnerUpdateNotification(userId, address) {
    return createNotification({
        userId,
        type: 'owner_update',
        title: 'New Property Update',
        message: `A new update has been posted for ${address}.`,
        relatedItemType: 'owner_update'
    });
}

export async function createSubmissionNotification(userId, submissionTitle) {
  return createNotification({
    userId,
    type: 'submission',
    title: 'New Form Submission',
    message: `A new submission was received for "${submissionTitle}".`,
    relatedItemType: 'submission'
  });
}

export async function createTaskNotification(userId, taskTitle, assignedByName) {
  return createNotification({
    userId,
    type: 'task_assigned',
    title: 'New Task Assigned',
    message: `${assignedByName || 'Admin'} assigned you a new task: "${taskTitle}"`,
    relatedItemType: 'task'
  });
}

export async function createDueDateNotification(userId, itemTitle, dueDate) {
  return createNotification({
    userId,
    type: 'due_date',
    title: 'Upcoming Due Date',
    message: `"${itemTitle}" is due on ${new Date(dueDate).toLocaleDateString()}.`,
    relatedItemType: 'task'
  });
}
