/**
 * Tabata Access Control Service
 * Manages free tier vs premium access
 *
 * Workout Programs: Free status from database is_free flag
 * Tabata: Free = entire Débutant program, Premium = everything else
 * Legacy: 3 free workouts kept for backward compatibility
 */

import type { TabataProgramId } from '../types/program'
import type { WorkoutProgram } from '../types/workoutProgram'

// ─── Tabata Program Access ───────────────────────────────────────

/** Program available without a subscription */
export const FREE_PROGRAM_ID: TabataProgramId = 'debutant'

/** Session ID prefix → program mapping */
const SESSION_PREFIX_MAP: Record<string, TabataProgramId> = {
  'deb-': 'debutant',
  'int-': 'intermediaire',
  'avc-': 'avance',
  'bur-': 'bureau',
}

/**
 * Check if a program is part of the free tier
 */
export function isFreeProgram(programId: TabataProgramId): boolean {
  return programId === FREE_PROGRAM_ID
}

/**
 * Check if user can access a tabata program
 */
export function canAccessProgram(programId: TabataProgramId, isPremium: boolean): boolean {
  if (isPremium) return true
  return isFreeProgram(programId)
}

/**
 * Check if user can access a specific tabata session
 * Extracts program from session ID prefix (e.g., 'deb-w1-s1' → 'debutant')
 */
export function canAccessSession(sessionId: string, isPremium: boolean): boolean {
  if (isPremium) return true
  for (const [prefix, programId] of Object.entries(SESSION_PREFIX_MAP)) {
    if (sessionId.startsWith(prefix)) {
      return isFreeProgram(programId)
    }
  }
  // Unknown prefix — deny by default
  return false
}

/**
 * Get the program ID from a session ID
 */
export function getSessionProgramId(sessionId: string): TabataProgramId | undefined {
  for (const [prefix, programId] of Object.entries(SESSION_PREFIX_MAP)) {
    if (sessionId.startsWith(prefix)) return programId
  }
  return undefined
}

// ─── Workout Program Access ─────────────────────────────────────

/**
 * Check if user can access a workout program
 * Free status is determined by the is_free flag in the database.
 * Falls back to level-based rules if isFree is undefined.
 */
export function canAccessWorkoutProgram(
  program: WorkoutProgram,
  isPremium: boolean,
): boolean {
  if (isPremium) return true
  // Handle boolean, string ("true"), and truthy values from Supabase/cache
  return program.isFree === true
}

// ─── Legacy Workout Access (kept for backward compatibility) ──

/** Workout IDs available without a subscription (legacy) */
export const FREE_WORKOUT_IDS: readonly string[] = [
  '1',   // Full Body Ignite — Beginner, 4 min (full-body)
  '11',  // Core Crusher — Intermediate, 4 min (core)
  '43',  // Dance Cardio — Beginner, 4 min (cardio)
] as const

/** Number of free workouts (for display in paywall copy) */
export const FREE_WORKOUT_COUNT = FREE_WORKOUT_IDS.length

/**
 * Check if a specific workout is part of the free tier (legacy)
 */
export function isFreeWorkout(workoutId: string): boolean {
  return FREE_WORKOUT_IDS.includes(workoutId)
}

/**
 * Check if user can access a workout (legacy + tabata)
 * Premium users can access everything; free users get free tier only
 */
export function canAccessWorkout(workoutId: string, isPremium: boolean): boolean {
  if (isPremium) return true
  // Check tabata session access
  if (canAccessSession(workoutId, false)) return true
  // Check legacy workout access
  return isFreeWorkout(workoutId)
}
