/**
 * Subscriptions + payments repository — cloud-agnostic via @bytelyst/datastore.
 */

import { getCollection } from '../../lib/datastore.js';
import type { SubscriptionDoc, PaymentDoc } from './types.js';

function subsCollection() {
  return getCollection<SubscriptionDoc>('subscriptions', '/userId');
}

function paymentsCollection() {
  return getCollection<PaymentDoc>('payments', '/userId');
}

// ── Subscriptions ──

export async function getByUserId(
  userId: string,
  productId: string
): Promise<SubscriptionDoc | null> {
  return subsCollection().findOne({
    filter: { productId, userId },
    sort: { createdAt: -1 },
  });
}

export async function getByStripeCustomerIdAnyProduct(
  stripeCustomerId: string
): Promise<SubscriptionDoc | null> {
  return subsCollection().findOne({
    filter: { stripeCustomerId },
    sort: { createdAt: -1 },
  });
}

export async function getByStripeCustomerId(
  stripeCustomerId: string,
  productId: string
): Promise<SubscriptionDoc | null> {
  return subsCollection().findOne({
    filter: { productId, stripeCustomerId },
    sort: { createdAt: -1 },
  });
}

export async function createSubscription(doc: SubscriptionDoc): Promise<SubscriptionDoc> {
  return subsCollection().create(doc);
}

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

// ── Payments ──

export async function getPaymentsByUser(
  userId: string,
  productId: string,
  limit = 50
): Promise<PaymentDoc[]> {
  return paymentsCollection().findMany({
    filter: { productId, userId },
    sort: { createdAt: -1 },
    limit,
  });
}

export async function createPayment(doc: PaymentDoc): Promise<PaymentDoc> {
  return paymentsCollection().create(doc);
}
