/**
 * useResumePlayback — stores and retrieves last playback position
 * per movie/episode for "Continue Watching" functionality.
 *
 * Storage key: `nadi_resume_{profileId}_{contentId}`
 * Value: JSON { position: number (ms), duration: number (ms), updatedAt: ISO string }
 *
 * Auto-clears entries older than 30 days or when position is within
 * 95% of duration (user finished watching).
 */

const STORAGE_PREFIX = "nadi_resume_";
const MAX_AGE_DAYS = 30;
const COMPLETION_THRESHOLD = 0.95;

interface ResumeData {
  position: number;
  duration: number;
  updatedAt: string;
}

/** Get the resume position for a content item (in milliseconds). Returns 0 if none. */
export const getResumePosition = (
  profileId: string | undefined,
  contentId: string
): number => {
  if (!profileId || !contentId) return 0;
  try {
    const key = `${STORAGE_PREFIX}${profileId}_${contentId}`;
    const raw = localStorage.getItem(key);
    if (!raw) return 0;

    const data: ResumeData = JSON.parse(raw);

    // Expired?
    const age = Date.now() - new Date(data.updatedAt).getTime();
    if (age > MAX_AGE_DAYS * 86400000) {
      localStorage.removeItem(key);
      return 0;
    }

    // Completed? (within 95% of duration)
    if (data.duration > 0 && data.position / data.duration >= COMPLETION_THRESHOLD) {
      localStorage.removeItem(key);
      return 0;
    }

    // Must be at least 10 seconds in to be worth resuming
    if (data.position < 10000) return 0;

    return data.position;
  } catch {
    return 0;
  }
};

/** Save the current playback position. */
export const saveResumePosition = (
  profileId: string | undefined,
  contentId: string,
  positionMs: number,
  durationMs: number
): void => {
  if (!profileId || !contentId || positionMs <= 0) return;
  try {
    const key = `${STORAGE_PREFIX}${profileId}_${contentId}`;

    // If completed, remove instead of saving
    if (durationMs > 0 && positionMs / durationMs >= COMPLETION_THRESHOLD) {
      localStorage.removeItem(key);
      return;
    }

    const data: ResumeData = {
      position: Math.floor(positionMs),
      duration: Math.floor(durationMs),
      updatedAt: new Date().toISOString(),
    };
    localStorage.setItem(key, JSON.stringify(data));
  } catch {
    // localStorage full or unavailable — ignore
  }
};

/** Clear resume position (e.g., user clicks "Start from beginning"). */
export const clearResumePosition = (
  profileId: string | undefined,
  contentId: string
): void => {
  if (!profileId || !contentId) return;
  try {
    localStorage.removeItem(`${STORAGE_PREFIX}${profileId}_${contentId}`);
  } catch {
    // ignore
  }
};

/** Clean up old resume entries (call on app boot). */
export const cleanupOldResumes = (): void => {
  try {
    const now = Date.now();
    const keysToRemove: string[] = [];
    for (let i = 0; i < localStorage.length; i++) {
      const key = localStorage.key(i);
      if (!key || !key.startsWith(STORAGE_PREFIX)) continue;
      try {
        const data: ResumeData = JSON.parse(localStorage.getItem(key) || "");
        if (now - new Date(data.updatedAt).getTime() > MAX_AGE_DAYS * 86400000) {
          keysToRemove.push(key);
        }
      } catch {
        keysToRemove.push(key!);
      }
    }
    keysToRemove.forEach((k) => localStorage.removeItem(k));
  } catch {
    // ignore
  }
};
