/**
 * Feature flags repository — cloud-agnostic via @bytelyst/datastore.
 */

import { getCollection } from '../../lib/datastore.js';
import type { FeatureFlagDoc } from './types.js';

function collection() {
  return getCollection<FeatureFlagDoc>('feature_flags', '/productId');
}

export async function list(productId: string): Promise<FeatureFlagDoc[]> {
  return collection().findMany({
    filter: { productId },
    sort: { key: 1 },
  });
}

export async function getByKey(key: string, productId: string): Promise<FeatureFlagDoc | null> {
  return collection().findOne({
    filter: { productId, key },
  });
}

export async function create(doc: FeatureFlagDoc): Promise<FeatureFlagDoc> {
  return collection().create(doc);
}

export async function update(
  id: string,
  updates: Partial<FeatureFlagDoc>
): Promise<FeatureFlagDoc | null> {
  try {
    return await collection().update(id, id, { ...updates, updatedAt: new Date().toISOString() });
  } catch {
    return null;
  }
}

export async function remove(id: string): Promise<boolean> {
  try {
    await collection().delete(id, id);
    return true;
  } catch {
    return false;
  }
}
