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

export type ActivityCategory = 'system' | 'user' | 'automation';

interface LogActivityParams {
  userId: string;
  contactId: string;
  type: 'email' | 'sms' | 'call' | 'system';
  direction: 'inbound' | 'outbound' | 'log';
  subject?: string;
  bodyPreview?: string;
  category?: ActivityCategory;
}

/**
 * Log an activity for a contact
 */
export async function logActivity({
  userId,
  contactId,
  type,
  direction,
  subject,
  bodyPreview,
  category = 'user',
}: LogActivityParams): Promise<void> {
  try {
    const { error } = await supabase.from('activities').insert({
      user_id: userId,
      contact_id: contactId,
      type,
      direction,
      subject,
      body_preview: bodyPreview,
      status: 'logged',
      category,
    });

    if (error) {
      console.error('Failed to log activity:', error);
    }
  } catch (error) {
    console.error('Failed to log activity:', error);
  }
}

/**
 * Log a system activity (automated)
 */
export async function logSystemActivity(
  userId: string,
  contactId: string,
  subject: string,
  bodyPreview?: string
): Promise<void> {
  return logActivity({
    userId,
    contactId,
    type: 'system',
    direction: 'log',
    subject,
    bodyPreview,
    category: 'system',
  });
}

/**
 * Log task-related activities
 */
export async function logTaskActivity(
  userId: string,
  contactId: string | null,
  action: 'created' | 'completed' | 'updated' | 'deleted',
  taskTitle: string
): Promise<void> {
  if (!contactId) return;
  
  const subjects: Record<string, string> = {
    created: `Task created: ${taskTitle}`,
    completed: `Task completed: ${taskTitle}`,
    updated: `Task updated: ${taskTitle}`,
    deleted: `Task deleted: ${taskTitle}`,
  };

  return logSystemActivity(userId, contactId, subjects[action]);
}

/**
 * Log contact status change
 */
export async function logStatusChange(
  userId: string,
  contactId: string,
  oldStatus: string | null,
  newStatus: string
): Promise<void> {
  const subject = oldStatus 
    ? `Status changed from "${oldStatus}" to "${newStatus}"`
    : `Status set to "${newStatus}"`;
  
  return logSystemActivity(userId, contactId, subject);
}

/**
 * Log tag changes
 */
export async function logTagChange(
  userId: string,
  contactId: string,
  action: 'added' | 'removed',
  tagName: string
): Promise<void> {
  const subject = action === 'added' 
    ? `Tag added: ${tagName}` 
    : `Tag removed: ${tagName}`;
  
  return logSystemActivity(userId, contactId, subject);
}

/**
 * Log pipeline/stage changes
 */
export async function logPipelineChange(
  userId: string,
  contactId: string,
  stageName: string,
  pipelineName?: string
): Promise<void> {
  const subject = pipelineName 
    ? `Moved to "${stageName}" in "${pipelineName}" pipeline`
    : `Pipeline stage changed to "${stageName}"`;
  
  return logSystemActivity(userId, contactId, subject);
}

/**
 * Log contact field updates
 */
export async function logContactUpdate(
  userId: string,
  contactId: string,
  changedFields: string[]
): Promise<void> {
  if (changedFields.length === 0) return;
  
  const subject = `Contact updated: ${changedFields.join(', ')}`;
  return logSystemActivity(userId, contactId, subject);
}
