/* eslint-disable @typescript-eslint/no-unused-vars */
/**
 * Performance Profile Repository — Remote Diagnostics
 * Ingest and query performance profiling data.
 */

import { getCollection } from '../../lib/datastore.js';
import type {
  PerformanceProfileDoc,
  ProfileData,
  QueryProfilesInput,
} from './performance-profile-types.js';
import type { FilterMap } from '@bytelyst/datastore';

const PROFILES_CONTAINER = 'performance_profiles';

function profilesCollection() {
  return getCollection<PerformanceProfileDoc>(PROFILES_CONTAINER, '/pk');
}

/**
 * Ingest a performance profile.
 */
export async function ingestProfile(doc: PerformanceProfileDoc): Promise<{ id: string }> {
  const collection = profilesCollection();
  await collection.upsert(doc);
  return { id: doc.id };
}

/**
 * Get a performance profile by ID.
 */
export async function getProfile(
  productId: string,
  sessionId: string,
  profileId: string
): Promise<PerformanceProfileDoc | null> {
  const collection = profilesCollection();
  const pk = `${productId}:${sessionId}`;

  const results = await collection.findMany({
    filter: { pk, profileId },
    limit: 1,
  });

  return results[0] ?? null;
}

/**
 * Query performance profiles for a session.
 */
export async function queryProfiles(
  productId: string,
  sessionId: string,
  query: QueryProfilesInput
): Promise<{
  profiles: PerformanceProfileDoc[];
  total: number;
}> {
  const collection = profilesCollection();
  const pk = `${productId}:${sessionId}`;

  // Build filter dynamically
  const filter: Record<string, string> = { pk };
  if (query.profileType) {
    filter.profileType = query.profileType;
  }
  if (query.platform) {
    filter.platform = query.platform;
  }

  const results = await collection.findMany({
    filter,
    limit: query.limit,
  });

  return {
    profiles: results,
    total: results.length,
  };
}

/**
 * List all profiles for a product (admin query).
 */
export async function listProfilesForProduct(
  productId: string,
  limit: number = 50
): Promise<PerformanceProfileDoc[]> {
  const collection = profilesCollection();

  // Query by productId field (not pk prefix)
  const results = await collection.findMany({
    filter: { productId },
    limit,
  });

  return results;
}

/**
 * Delete a performance profile.
 */
export async function deleteProfile(
  productId: string,
  sessionId: string,
  profileId: string
): Promise<boolean> {
  const collection = profilesCollection();
  const pk = `${productId}:${sessionId}`;

  const results = await collection.findMany({
    filter: { pk, profileId },
    limit: 1,
  });

  if (results.length === 0) return false;

  // Soft delete
  await collection.upsert({
    ...results[0],
    profile: { type: results[0].profile.type, platform: results[0].platform } as ProfileData,
    updatedAt: new Date().toISOString(),
  });

  return true;
}
