/**
 * Database MCP Server - Analytics
 *
 * Provides Supabase analytics database queries.
 * Token savings: 20,000+ per operation (dashboard data, large result sets)
 *
 * Note: This connects to Supabase for extended analytics features
 * separate from the primary Prisma database.
 */

import { callMCPTool } from "../../client.js";

export interface DemoBookingAnalytics {
  totalBookings: number;
  byStatus: Record<string, number>;
  byService: Record<string, number>;
  byLocation: Record<string, number>;
  conversionRate: number;
  averageResponseTime: number;
  peakHours: Array<{ hour: number; count: number }>;
  recentTrend: Array<{ date: string; count: number }>;
}

export interface UserAnalytics {
  totalUsers: number;
  newUsersToday: number;
  newUsersThisWeek: number;
  newUsersThisMonth: number;
  byIndustry: Record<string, number>;
  byLocation: Record<string, number>;
  verificationRate: number;
  activeUsers: number;
}

export interface RevenueAnalytics {
  mrr: number; // Monthly Recurring Revenue
  arr: number; // Annual Recurring Revenue
  totalRevenue: number;
  byPlan: Record<string, number>;
  churnRate: number;
  ltv: number; // Lifetime Value
  newMRR: number;
  lostMRR: number;
}

export interface GetAnalyticsInput {
  startDate?: string;
  endDate?: string;
  groupBy?: "day" | "week" | "month";
}

/**
 * Get demo booking analytics from Supabase.
 *
 * @param input - Date range and grouping options
 * @returns Comprehensive booking analytics
 *
 * @example
 * ```typescript
 * // Get current month analytics
 * const analytics = await getDemoBookingAnalytics({
 *   startDate: '2025-11-01',
 *   endDate: '2025-11-30'
 * });
 *
 * console.log(`Total: ${analytics.totalBookings}`);
 * console.log(`Conversion: ${analytics.conversionRate}%`);
 * console.log('Top services:', Object.entries(analytics.byService).slice(0, 5));
 * console.log('Peak hours:', analytics.peakHours);
 * ```
 */
export async function getDemoBookingAnalytics(
  input: GetAnalyticsInput = {},
): Promise<DemoBookingAnalytics> {
  return callMCPTool<DemoBookingAnalytics>(
    "database__get_demo_booking_analytics",
    input,
  );
}

/**
 * Get user analytics from Supabase.
 *
 * @param input - Date range options
 * @returns User growth and distribution analytics
 *
 * @example
 * ```typescript
 * const analytics = await getUserAnalytics();
 *
 * console.log(`Total users: ${analytics.totalUsers}`);
 * console.log(`New this week: ${analytics.newUsersThisWeek}`);
 * console.log(`Verification rate: ${analytics.verificationRate}%`);
 * console.log('Top industries:', Object.entries(analytics.byIndustry).slice(0, 5));
 * ```
 */
export async function getUserAnalytics(
  input: GetAnalyticsInput = {},
): Promise<UserAnalytics> {
  return callMCPTool<UserAnalytics>("database__get_user_analytics", input);
}

/**
 * Get revenue analytics from Supabase.
 *
 * @param input - Date range options
 * @returns Revenue metrics and subscription data
 *
 * @example
 * ```typescript
 * const revenue = await getRevenueAnalytics();
 *
 * console.log(`MRR: $${revenue.mrr.toLocaleString()}`);
 * console.log(`ARR: $${revenue.arr.toLocaleString()}`);
 * console.log(`Churn Rate: ${revenue.churnRate}%`);
 * console.log(`LTV: $${revenue.ltv.toLocaleString()}`);
 * console.log('Revenue by plan:', revenue.byPlan);
 * ```
 */
export async function getRevenueAnalytics(
  input: GetAnalyticsInput = {},
): Promise<RevenueAnalytics> {
  return callMCPTool<RevenueAnalytics>(
    "database__get_revenue_analytics",
    input,
  );
}

/**
 * Get company profiles from Supabase (extended data not in Prisma).
 *
 * @param limit - Maximum records to return
 * @returns Array of company profile objects
 *
 * @example
 * ```typescript
 * const profiles = await getCompanyProfiles(50);
 *
 * // Analyze industry distribution
 * const byIndustry = profiles.reduce((acc, p) => {
 *   const industry = p.industry || 'Other';
 *   acc[industry] = (acc[industry] || 0) + 1;
 *   return acc;
 * }, {});
 *
 * console.log('Companies by industry:', byIndustry);
 * ```
 */
export async function getCompanyProfiles(limit = 100): Promise<any[]> {
  return callMCPTool<any[]>("database__get_company_profiles", { limit });
}

/**
 * Get audit logs from Supabase for security analysis.
 *
 * @param input - Filter parameters
 * @returns Array of audit log entries
 *
 * @example
 * ```typescript
 * const logs = await getAuditLogs({
 *   startDate: '2025-11-01',
 *   limit: 100
 * });
 *
 * // Analyze security events
 * const failedLogins = logs.filter(l => l.action === 'LOGIN_FAILED');
 * const byUser = failedLogins.reduce((acc, l) => {
 *   acc[l.userEmail] = (acc[l.userEmail] || 0) + 1;
 *   return acc;
 * }, {});
 *
 * console.log(`Failed login attempts: ${failedLogins.length}`);
 * console.log('Top 5 users with failures:', Object.entries(byUser).slice(0, 5));
 * ```
 */
export async function getAuditLogs(
  input: GetAnalyticsInput & { action?: string; limit?: number } = {},
): Promise<any[]> {
  return callMCPTool<any[]>("database__get_audit_logs", input);
}

export default {
  getDemoBookingAnalytics,
  getUserAnalytics,
  getRevenueAnalytics,
  getCompanyProfiles,
  getAuditLogs,
};
