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

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

function collection() {
  return getCollection<PlanConfig>('plans', '/productId');
}

export async function list(productId: string): Promise<PlanConfig[]> {
  const results = await collection().findMany({
    filter: { productId },
    sort: { price: 1 },
  });

  // If no plans in DB yet, return defaults
  if (results.length === 0) {
    return getDefaults(productId);
  }
  return results;
}

export async function getByName(name: string, productId: string): Promise<PlanConfig | null> {
  return collection().findOne({
    filter: { productId, name },
  });
}

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

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

export function getDefaults(productId: string): PlanConfig[] {
  const now = new Date().toISOString();
  return DEFAULT_PLANS.map(p => ({
    ...p,
    id: `plan_${productId}_${p.name}`,
    productId,
    createdAt: now,
    updatedAt: now,
  }));
}
