import { api } from "@/lib/api"
import type { CreateReminderPayload, NotificationsResponse } from "@/types/reminders"

export const createReminder = ["reminders", "create"]
export const getReminders = ["reminders", "list"]
export const getReminderById = (id: string) => ["reminders", "detail", id]
export const getReminderDefaults = ["reminders", "defaults"]
export const getNotifications = ["notifications", "list"]

export async function createNewReminder(payload: CreateReminderPayload) {
  const { data } = await api.post("/reminders", payload)
  return data
}

export async function fetchReminders() {
  const { data } = await api.get("/reminders")
  return data
}

export async function removeReminder(id: string) {
  const { data } = await api.delete(`/reminders/${id}`)
  return data
}

export async function updateReminder(id: string, payload: Partial<CreateReminderPayload>) {
  const { data } = await api.put(`/reminders/${id}`, payload)
  return data
}

export async function getReminderDetails(id: string) {
  const { data } = await api.get(`/reminders/${id}`)
  return data
}

export async function fetchReminderDefaults() {
  const { data } = await api.get("/reminders/defaults")
  return data
}

export async function fetchNotifications(type?: string): Promise<NotificationsResponse> {
  try {
    const { data } = await api.get("/reminders/storednotifications", {
      params: type && type !== 'all' ? { type } : {}
    })
    // Handle both direct array response and wrapped response
    return Array.isArray(data) ? data : data?.notifications || []
  } catch (error) {
    console.error("Notifications API error:", error)
    return []
  }
}

export const markAllNotificationsRead = ["notifications", "mark-all-read"]

export async function markAllNotificationsAsRead() {
  const { data } = await api.patch("/reminders/notifications/mark-all-read")
  return data
}

export async function markNotificationRead(id: string) {
  const { data } = await api.post(`/reminders/notifications/mark-read/${id}`)
  return data
}

export async function getStoredNotificationById(id: string) {
  const { data } = await api.get(`/reminders/storednotification/${id}`)
  return data
}
