import { db } from "./db";
import { activityLogs } from "@shared/schema";
import type { InsertActivityLog } from "@shared/schema";
import type { Request } from "express";

interface LogActivityParams {
  userId: number;
  action: string;
  resourceType?: string;
  resourceId?: number;
  resourceName?: string;
  details?: any;
  req?: Request;
}

export async function logActivity({
  userId,
  action,
  resourceType,
  resourceId,
  resourceName,
  details,
  req
}: LogActivityParams) {
  try {
    const logData: InsertActivityLog = {
      userId,
      action,
      resourceType: resourceType || null,
      resourceId: resourceId || null,
      resourceName: resourceName || null,
      details: details ? JSON.stringify(details) : null,
      ipAddress: req ? getClientIP(req) : null,
      userAgent: req ? req.get('User-Agent') || null : null,
    };

    await db.insert(activityLogs).values(logData);
    
    console.log(`[ACTIVITY LOG] User ${userId} - ${action}${resourceType ? ` on ${resourceType}` : ''}${resourceId ? ` (ID: ${resourceId})` : ''}`);
  } catch (error) {
    console.error('[ACTIVITY LOG ERROR]', error);
    // Don't throw error to avoid breaking the main functionality
  }
}

function getClientIP(req: Request): string | null {
  return (
    req.ip ||
    req.connection?.remoteAddress ||
    req.socket?.remoteAddress ||
    (req.headers['x-forwarded-for'] as string)?.split(',')[0]?.trim() ||
    null
  );
}

// Helper functions for common logging scenarios
export const ActivityLogger = {
  // Authentication actions
  login: (userId: number, req?: Request) => 
    logActivity({ userId, action: 'login', req }),
  
  logout: (userId: number, req?: Request) => 
    logActivity({ userId, action: 'logout', req }),

  // Client management actions
  createClient: (userId: number, clientId: number, clientName: string, req?: Request) =>
    logActivity({ 
      userId, 
      action: 'client_create', 
      resourceType: 'client', 
      resourceId: clientId,
      resourceName: clientName,
      req 
    }),

  editClient: (userId: number, clientId: number, clientName: string, changes: any, req?: Request) =>
    logActivity({ 
      userId, 
      action: 'client_edit', 
      resourceType: 'client', 
      resourceId: clientId,
      resourceName: clientName,
      details: changes,
      req 
    }),

  deleteClient: (userId: number, clientId: number, clientName: string, req?: Request) =>
    logActivity({ 
      userId, 
      action: 'client_delete', 
      resourceType: 'client', 
      resourceId: clientId,
      resourceName: clientName,
      req 
    }),

  viewClient: (userId: number, clientId: number, clientName: string, req?: Request) =>
    logActivity({ 
      userId, 
      action: 'client_view', 
      resourceType: 'client', 
      resourceId: clientId,
      resourceName: clientName,
      req 
    }),

  // Search and filter actions
  search: (userId: number, searchTerm: string, category?: string, req?: Request) =>
    logActivity({ 
      userId, 
      action: 'search', 
      resourceType: 'search',
      details: { searchTerm, category },
      req 
    }),

  // API key actions
  createApiKey: (userId: number, keyName: string, req?: Request) =>
    logActivity({ 
      userId, 
      action: 'apikey_create', 
      resourceType: 'apikey',
      resourceName: keyName,
      req 
    }),

  deleteApiKey: (userId: number, keyName: string, req?: Request) =>
    logActivity({ 
      userId, 
      action: 'apikey_delete', 
      resourceType: 'apikey',
      resourceName: keyName,
      req 
    }),

  // Data sync actions
  syncData: (userId: number, syncType: string, details?: any, req?: Request) =>
    logActivity({ 
      userId, 
      action: 'data_sync', 
      resourceType: 'sync',
      resourceName: syncType,
      details,
      req 
    }),

  // Page visits
  visitPage: (userId: number, page: string, req?: Request) =>
    logActivity({ 
      userId, 
      action: 'page_visit', 
      resourceType: 'page',
      resourceName: page,
      req 
    }),

  // Staff notifications
  createNotification: (userId: number, title: string, req?: Request) =>
    logActivity({ 
      userId, 
      action: 'notification_create', 
      resourceType: 'notification',
      resourceName: title,
      req 
    }),

  editNotification: (userId: number, title: string, req?: Request) =>
    logActivity({ 
      userId, 
      action: 'notification_edit', 
      resourceType: 'notification',
      resourceName: title,
      req 
    }),

  deleteNotification: (userId: number, title: string, req?: Request) =>
    logActivity({ 
      userId, 
      action: 'notification_delete', 
      resourceType: 'notification',
      resourceName: title,
      req 
    }),
};