import type { FilterMap } from '@bytelyst/datastore';
import { getCollection } from '../../lib/datastore.js';
import type { DeliveryLogDoc } from './types.js';

function collection() {
  return getCollection<DeliveryLogDoc>('delivery_log', '/pk');
}

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

export async function updateDeliveryLog(doc: DeliveryLogDoc): Promise<DeliveryLogDoc> {
  return collection().upsert(doc);
}

export async function getDeliveryLog(id: string, pk: string): Promise<DeliveryLogDoc | null> {
  return collection().findById(id, pk);
}

export async function listDeliveryLogs(
  productId: string,
  options?: { channel?: string; status?: string; limit?: number }
): Promise<DeliveryLogDoc[]> {
  const limit = Math.min(options?.limit ?? 50, 200);
  const filter: FilterMap = {
    pk: { $startsWith: productId },
  };
  if (options?.channel) filter.channel = options.channel;
  if (options?.status) filter.status = options.status;

  return collection().findMany({
    filter,
    sort: { createdAt: -1 },
    limit,
  });
}

export async function getDeliveryStats(productId: string): Promise<{
  total: number;
  sent: number;
  failed: number;
  byChannel: Record<string, number>;
}> {
  // Fetch all matching docs and aggregate in-memory
  const docs = await collection().findMany({
    filter: { pk: { $startsWith: productId } },
  });

  const byStatus: Record<string, number> = {};
  const byChannel: Record<string, number> = {};

  for (const doc of docs) {
    byStatus[doc.status] = (byStatus[doc.status] ?? 0) + 1;
    byChannel[doc.channel] = (byChannel[doc.channel] ?? 0) + 1;
  }

  return {
    total: docs.length,
    sent: byStatus['sent'] ?? 0,
    failed: byStatus['failed'] ?? 0,
    byChannel,
  };
}
