import {
  ReferralRelationship,
  ReferralReward,
  ReferralAdminStats,
  ReferralAdminStatsExtended,
  PaginatedResult,
  ReferralStatus,
  RewardStatus,
  UserReferralStatus,
  UserCircleRelationship,
  UserPointTransaction,
  UserPointBalance,
} from '@/domain/entities/referral';

function getAuthHeaders(): HeadersInit {
  const token = localStorage.getItem('token');
  const tenantId = localStorage.getItem('tenantId');
  return {
    Authorization: `Bearer ${token}`,
    'Content-Type': 'application/json',
    ...(tenantId ? { 'X-Tenant-Id': tenantId } : {}),
  };
}

const BASE = '/api/proxy';

export async function getAdminReferralStats(): Promise<ReferralAdminStatsExtended> {
  const res = await fetch(`${BASE}/api/v1/referral/admin/stats`, {
    headers: getAuthHeaders(),
  });
  if (!res.ok) throw new Error(`Failed to fetch referral stats: ${res.status}`);
  return res.json();
}

export async function listAdminRelationships(params: {
  status?: ReferralStatus;
  limit?: number;
  offset?: number;
}): Promise<PaginatedResult<ReferralRelationship>> {
  const q = new URLSearchParams();
  if (params.status) q.set('status', params.status);
  if (params.limit != null) q.set('limit', String(params.limit));
  if (params.offset != null) q.set('offset', String(params.offset));
  const res = await fetch(`${BASE}/api/v1/referral/admin/relationships?${q}`, {
    headers: getAuthHeaders(),
  });
  if (!res.ok) throw new Error(`Failed to fetch relationships: ${res.status}`);
  return res.json();
}

export async function listAdminRewards(params: {
  status?: RewardStatus;
  limit?: number;
  offset?: number;
}): Promise<PaginatedResult<ReferralReward>> {
  const q = new URLSearchParams();
  if (params.status) q.set('status', params.status);
  if (params.limit != null) q.set('limit', String(params.limit));
  if (params.offset != null) q.set('offset', String(params.offset));
  const res = await fetch(`${BASE}/api/v1/referral/admin/rewards?${q}`, {
    headers: getAuthHeaders(),
  });
  if (!res.ok) throw new Error(`Failed to fetch rewards: ${res.status}`);
  return res.json();
}

export async function listAdminUserCircles(params: {
  status?: UserReferralStatus;
  limit?: number;
  offset?: number;
}): Promise<PaginatedResult<UserCircleRelationship>> {
  const q = new URLSearchParams();
  if (params.status) q.set('status', params.status);
  if (params.limit != null) q.set('limit', String(params.limit));
  if (params.offset != null) q.set('offset', String(params.offset));
  const res = await fetch(`${BASE}/api/v1/referral/admin/user-circles?${q}`, {
    headers: getAuthHeaders(),
  });
  if (!res.ok) throw new Error(`Failed to fetch user circles: ${res.status}`);
  return res.json();
}

export async function listAdminUserPoints(params: {
  limit?: number;
  offset?: number;
}): Promise<PaginatedResult<UserPointTransaction>> {
  const q = new URLSearchParams();
  if (params.limit != null) q.set('limit', String(params.limit));
  if (params.offset != null) q.set('offset', String(params.offset));
  const res = await fetch(`${BASE}/api/v1/referral/admin/user-points?${q}`, {
    headers: getAuthHeaders(),
  });
  if (!res.ok) throw new Error(`Failed to fetch user points: ${res.status}`);
  return res.json();
}

export async function listAdminUserBalances(params: {
  limit?: number;
  offset?: number;
}): Promise<PaginatedResult<UserPointBalance>> {
  const q = new URLSearchParams();
  if (params.limit != null) q.set('limit', String(params.limit));
  if (params.offset != null) q.set('offset', String(params.offset));
  const res = await fetch(`${BASE}/api/v1/referral/admin/user-balances?${q}`, {
    headers: getAuthHeaders(),
  });
  if (!res.ok) throw new Error(`Failed to fetch user balances: ${res.status}`);
  return res.json();
}
