/**
 * Feature flags repository — cloud-agnostic via @bytelyst/datastore.
 *
 * Three collections:
 * - feature_flags   — flag documents (partition: /productId)
 * - flag_segments   — user segments (partition: /productId)
 * - flag_audit_log  — change audit trail (partition: /productId)
 */

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

// ── Flags ───────────────────────────────────────────────────────────────────

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

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

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

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

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

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

// ── Segments ────────────────────────────────────────────────────────────────

function segmentCollection() {
  return getCollection<SegmentDoc>('flag_segments', '/productId');
}

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

export async function getSegmentByKey(key: string, productId: string): Promise<SegmentDoc | null> {
  return segmentCollection().findOne({
    filter: { productId, key },
  });
}

export async function createSegment(doc: SegmentDoc): Promise<SegmentDoc> {
  return segmentCollection().create(doc);
}

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

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

// ── Audit Log ───────────────────────────────────────────────────────────────

function auditCollection() {
  return getCollection<FlagAuditDoc>('flag_audit_log', '/productId');
}

export async function createAuditEntry(doc: FlagAuditDoc): Promise<FlagAuditDoc> {
  return auditCollection().create(doc);
}

export async function listAuditLog(
  productId: string,
  flagKey?: string,
  limit = 50
): Promise<FlagAuditDoc[]> {
  const filter = flagKey ? { productId, flagKey } : { productId };

  const all = await auditCollection().findMany({
    filter,
    sort: { timestamp: -1 },
  });
  return all.slice(0, limit);
}
