/**
 * Growth Service API client for the admin dashboard.
 * Uses @bytelyst/api-client shared package.
 *
 * Replaces direct Cosmos DB calls for invitations, referrals, and promos.
 * Calls consolidated platform-service on port 4003.
 */

import { createApiClient } from '@bytelyst/api-client';

const growthApi = createApiClient({
  baseUrl: `${process.env.PLATFORM_SERVICE_URL || 'http://localhost:4003'}/api`,
  defaultHeaders: {
    'x-product-id': process.env.PRODUCT_ID || 'lysnrai',
  },
});

// ── Invitations ──────────────────────────────────────────────────

export async function listInvitations(limit = 100, offset = 0) {
  return growthApi.fetch<{ invitations: unknown[]; count: number }>(
    `/invitations?limit=${limit}&offset=${offset}`
  );
}

export async function getInvitation(id: string) {
  return growthApi.fetch<unknown>(`/invitations/${id}`);
}

export async function createInvitation(body: Record<string, unknown>) {
  return growthApi.fetch<unknown>('/invitations', {
    method: 'POST',
    body: JSON.stringify(body),
  });
}

export async function updateInvitation(id: string, body: Record<string, unknown>) {
  return growthApi.fetch<unknown>(`/invitations/${id}`, {
    method: 'PUT',
    body: JSON.stringify(body),
  });
}

export async function deleteInvitation(id: string) {
  return growthApi.fetch<void>(`/invitations/${id}`, { method: 'DELETE' });
}

export async function countInvitations() {
  return growthApi.fetch<{ count: number }>('/invitations/count');
}

export async function bulkCreateInvitations(body: unknown[]) {
  return growthApi.fetch<{
    total: number;
    created: number;
    failed: number;
    invitations: unknown[];
    errors: { index: number; error: string }[];
  }>('/invitations/bulk', {
    method: 'POST',
    body: JSON.stringify(body),
  });
}

// ── Referrals ────────────────────────────────────────────────────

export async function listReferrals(limit = 100, offset = 0) {
  return growthApi.fetch<{ referrals: unknown[]; count: number }>(
    `/referrals?limit=${limit}&offset=${offset}`
  );
}

export async function getReferralStats() {
  return growthApi.fetch<{ total: number; completed: number; rewarded: number }>(
    '/referrals/stats'
  );
}

// ── Promos ───────────────────────────────────────────────────────

export async function listPromos(active?: boolean) {
  const qs = active !== undefined ? `?active=${active}` : '';
  return growthApi.fetch<{ promos: unknown[] }>(`/promos${qs}`);
}

export async function createPromo(body: Record<string, unknown>) {
  return growthApi.fetch<unknown>('/promos', {
    method: 'POST',
    body: JSON.stringify(body),
  });
}

export async function validatePromo(code: string) {
  return growthApi.fetch<{ valid: boolean; promo: unknown }>('/promos/validate', {
    method: 'POST',
    body: JSON.stringify({ code }),
  });
}

export async function deactivatePromo(id: string) {
  return growthApi.fetch<unknown>(`/promos/${id}/deactivate`, { method: 'PUT' });
}
