/**
 * EngagementTracker
 *
 * Story 3.4: Service for tracking user engagement
 *
 * Uses completed drafts count as the engagement metric.
 * User is considered "engaged" when they have at least 1 completed draft.
 *
 * This is used to conditionally show the install prompt - only after
 * the user has engaged with the app.
 *
 * MVP: Uses existing drafts table with status='completed'
 * Post-MVP: Could create separate engagement tracking table
 */

import { db } from '@/lib/db';

/**
 * EngagementTracker
 *
 * Tracks user engagement to determine when to show install prompt.
 * Based on completed drafts count.
 */
export class EngagementTracker {
  /**
   * Get the count of completed sessions (drafts with status='completed')
   *
   * @returns Promise<number> - Count of completed drafts
   */
  static async getCompletedSessionCount(): Promise<number> {
    try {
      const count = await db.drafts
        .where('status')
        .equals('completed')
        .count();

      return count;
    } catch (error) {
      console.error('[EngagementTracker] Error getting completed session count:', error);
      return 0;
    }
  }

  /**
   * Check if the user has engaged with the app
   *
   * User is considered engaged if they have at least 1 completed draft.
   *
   * @returns Promise<boolean> - true if user has engaged
   */
  static async hasEngaged(): Promise<boolean> {
    const count = await this.getCompletedSessionCount();
    return count > 0;
  }

  /**
   * Get engagement level category
   *
   * @returns Promise<'none' | 'low' | 'medium' | 'high'>
   * - none: 0 completed drafts
   * - low: 1-2 completed drafts
   * - medium: 3-5 completed drafts
   * - high: 6+ completed drafts
   */
  static async getEngagementLevel(): Promise<'none' | 'low' | 'medium' | 'high'> {
    const count = await this.getCompletedSessionCount();

    if (count === 0) return 'none';
    if (count <= 2) return 'low';
    if (count <= 5) return 'medium';
    return 'high';
  }
}
