/**
 * Referrals repository — cloud-agnostic via @bytelyst/datastore.
 * Consolidated from admin-dashboard-web + user-dashboard-web repos.
 */

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

function collection() {
  return getCollection<ReferralDoc>('referrals', '/referrerId');
}

export async function listAll(limit = 100, offset = 0, productId?: string): Promise<ReferralDoc[]> {
  const results = await collection().findMany({
    filter: { productId: productId ?? '' },
    sort: { createdAt: -1 },
    limit: limit + offset,
  });
  return results.slice(offset);
}

export async function getByReferrer(referrerId: string, productId: string): Promise<ReferralDoc[]> {
  return collection().findMany({
    filter: { productId, referrerId },
    sort: { createdAt: -1 },
  });
}

export async function getByReferredEmail(
  email: string,
  productId: string
): Promise<ReferralDoc | null> {
  return collection().findOne({
    filter: { productId, referredEmail: email.toLowerCase() },
    sort: { createdAt: -1 },
  });
}

export async function getById(id: string, referrerId: string): Promise<ReferralDoc | null> {
  try {
    return await collection().findById(id, referrerId);
  } catch {
    return null;
  }
}

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

export async function update(
  id: string,
  referrerId: string,
  updates: Partial<ReferralDoc>
): Promise<ReferralDoc | null> {
  try {
    return await collection().update(id, referrerId, updates);
  } catch {
    return null;
  }
}

export async function countReferrals(productId: string): Promise<{
  total: number;
  completed: number;
  rewarded: number;
}> {
  const total = await collection().count({ productId });
  const completed = await collection().count({
    productId,
    status: { $in: ['signed_up', 'subscribed', 'rewarded'] },
  });
  const rewarded = await collection().count({
    productId,
    status: 'rewarded',
  });
  return { total, completed, rewarded };
}
