import { getToken } from "./auth";

const API_BASE = process.env.NEXT_PUBLIC_API_BASE || "http://localhost:4000";

const request = async <T>(path: string, options: RequestInit = {}) => {
  const token = getToken();
  const res = await fetch(`${API_BASE}${path}`, {
    ...options,
    headers: {
      "Content-Type": "application/json",
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
      ...(options.headers || {}),
    },
  });
  if (!res.ok) {
    throw new Error(await res.text());
  }
  return (await res.json()) as T;
};

export const api = {
  login: (payload: { username: string; password: string }) =>
    request<{ token: string; user: { id: string; username: string } }>("/api/auth/login", {
      method: "POST",
      body: JSON.stringify(payload),
    }),
  register: (payload: { username: string; password: string; inviteCode: string }) =>
    request<{ token: string; user: { id: string; username: string } }>("/api/auth/register", {
      method: "POST",
      body: JSON.stringify(payload),
    }),
  getTodos: () => request("/api/todos"),
  createTodo: (payload: unknown) =>
    request("/api/todos", { method: "POST", body: JSON.stringify(payload) }),
  deleteTodo: (id: string) => request(`/api/todos/${id}`, { method: "DELETE" }),
  checkInTodo: (id: string) => request(`/api/todos/${id}/check-in`, { method: "POST" }),
  getReminderTasks: () => request("/api/reminder-tasks"),
  createReminderTask: (payload: unknown) =>
    request("/api/reminder-tasks", { method: "POST", body: JSON.stringify(payload) }),
  deleteReminderTask: (id: string) =>
    request(`/api/reminder-tasks/${id}`, { method: "DELETE" }),
  getUsers: (query?: string) =>
    request(`/api/users${query ? `?query=${encodeURIComponent(query)}` : ""}`),
  getNotifications: () => request("/api/notifications?status=unread"),
  markNotificationRead: (id: string) =>
    request(`/api/notifications/${id}/read`, { method: "POST" }),
  markAllNotificationsRead: () =>
    request("/api/notifications/read-all", { method: "POST" }),
  getMe: () => request("/api/me"),
  updateSettings: (payload: unknown) =>
    request("/api/me/settings", { method: "PUT", body: JSON.stringify(payload) }),
  uploadAvatar: async (file: File): Promise<{ avatarUrl: string }> => {
    const token = getToken();
    const formData = new FormData();
    formData.append("avatar", file);

    const res = await fetch(`${API_BASE}/api/me/avatar`, {
      method: "POST",
      headers: {
        ...(token ? { Authorization: `Bearer ${token}` } : {}),
      },
      body: formData,
    });

    if (!res.ok) {
      throw new Error(await res.text());
    }
    return res.json();
  },
  // Password management
  changePassword: (payload: { currentPassword: string; newPassword: string }) =>
    request("/api/me/password", { method: "PUT", body: JSON.stringify(payload) }),
  // Invite management
  getInvites: () => request("/api/invites"),
  createInvite: (payload: { maxUses?: number; expiresInDays?: number }) =>
    request("/api/invites", { method: "POST", body: JSON.stringify(payload) }),
  getInvite: (id: string) => request(`/api/invites/${id}`),
  revokeInvite: (id: string) =>
    request(`/api/invites/${id}/revoke`, { method: "POST" }),
};
