import { supabase } from '@/integrations/supabase/client';
import { sendEmailViaSMTP } from './sendEmailViaSMTP';

/**
 * Sends an in-app notification + optional SMTP email when a task is assigned.
 */
export async function notifyTaskAssignment(taskTitle, assignedToUserId, assignedByName) {
  if (!assignedToUserId) return;

  try {
    // 1. Create in-app notification via RPC (bypasses RLS)
    await supabase.rpc('insert_notification', {
      p_user_id: assignedToUserId,
      p_type: 'task_assigned',
      p_title: 'New Task Assigned',
      p_message: `${assignedByName || 'Admin'} assigned you: "${taskTitle}"`,
      p_related_item_type: 'task',
      p_link: '/dashboard/tasks',
    });

    // 2. Look up user email for SMTP notification
    const { data: profile } = await supabase
      .from('profiles')
      .select('full_name, user_id')
      .eq('user_id', assignedToUserId)
      .single();

    if (!profile) return;

    // Get the user's email from the assignedToUserId by checking profiles/owners or use Supabase auth
    // We'll look up the email from the email_senders for SMTP, and the user's email from all_users or owners
    const { data: senders } = await supabase
      .from('email_senders')
      .select('id')
      .eq('is_active', true)
      .eq('verified', true)
      .limit(1);

    if (!senders?.length) {
      console.log('No active SMTP sender configured, skipping email notification');
      return;
    }

    // Try to get recipient email - check if they have an owner record or use a known email
    // For staff users, we look up via supabase auth admin (not available client-side)
    // Instead, invoke edge function for email sending
    await supabase.functions.invoke('send-task-notification-email', {
      body: {
        task_title: taskTitle,
        assigned_to_user_id: assignedToUserId,
        assigned_by_name: assignedByName || 'Admin',
        sender_id: senders[0].id,
      },
    });
  } catch (error) {
    console.error('Task notification error:', error);
  }
}
