import {
  NotificationItem,
  NotificationListResult,
  CreateNotificationPayload,
} from '@/domain/entities/notification';

function getAuthHeaders(): HeadersInit {
  const token = typeof window !== 'undefined' ? localStorage.getItem('token') : null;
  return {
    Authorization: `Bearer ${token ?? ''}`,
    'Content-Type': 'application/json',
  };
}

const BASE = '/api/proxy';

export async function listAdminNotifications(params: {
  type?: string;
  targetType?: string;
  limit?: number;
  offset?: number;
}): Promise<NotificationListResult> {
  const q = new URLSearchParams();
  if (params.type) q.set('type', params.type);
  if (params.targetType) q.set('targetType', params.targetType);
  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/notifications/admin?${q}`, {
    headers: getAuthHeaders(),
  });
  if (!res.ok) throw new Error(`Failed to fetch notifications: ${res.status}`);
  return res.json();
}

export async function getAdminNotification(id: string): Promise<NotificationItem> {
  const res = await fetch(`${BASE}/api/v1/notifications/admin/${id}`, {
    headers: getAuthHeaders(),
  });
  if (!res.ok) throw new Error(`Failed to fetch notification: ${res.status}`);
  return res.json();
}

export async function createNotification(payload: CreateNotificationPayload): Promise<NotificationItem> {
  const res = await fetch(`${BASE}/api/v1/notifications/admin`, {
    method: 'POST',
    headers: getAuthHeaders(),
    body: JSON.stringify(payload),
  });
  if (!res.ok) throw new Error(`Failed to create notification: ${res.status}`);
  return res.json();
}

export async function updateNotification(
  id: string,
  payload: Partial<CreateNotificationPayload>,
): Promise<NotificationItem> {
  const res = await fetch(`${BASE}/api/v1/notifications/admin/${id}`, {
    method: 'PUT',
    headers: getAuthHeaders(),
    body: JSON.stringify(payload),
  });
  if (!res.ok) throw new Error(`Failed to update notification: ${res.status}`);
  return res.json();
}

export async function deleteNotification(id: string): Promise<void> {
  const res = await fetch(`${BASE}/api/v1/notifications/admin/${id}`, {
    method: 'DELETE',
    headers: getAuthHeaders(),
  });
  if (!res.ok) throw new Error(`Failed to delete notification: ${res.status}`);
}

export async function toggleNotification(id: string, isEnabled: boolean): Promise<NotificationItem> {
  return updateNotification(id, { isEnabled });
}
