import axios, { type AxiosResponse } from "axios"; const setJwtToken = (token: string) => window.localStorage.setItem("paysplit-jwt", token); export const getJwtToken = () => window.localStorage.getItem("paysplit-jwt"); const getJwtHeader = () => { const token = getJwtToken(); if (!token) { throw new Error("Unauthenticated"); } return { headers: { authorization: `Bearer ${token}`, }, }; }; interface AccessResponse { jwtToken: string; } export const login = async (name: string, password: string) => { const response = (await axios.post("/access/login", { name, password, })) as AxiosResponse; setJwtToken(response.data.jwtToken); }; export const registerUser = async (name: string, password: string) => { const response = (await axios.post("/access/register", { name, password, })) as AxiosResponse; setJwtToken(response.data.jwtToken); }; export const startBuyFlow = (quantity: number) => axios.post("/buy/start", { quantity }, getJwtHeader()) as Promise< AxiosResponse<{ url: string }, unknown, {}> >; export const completeBuyFlow = (purchaseId: string) => axios.post("/buy/complete", { purchaseId }, getJwtHeader()) as Promise< AxiosResponse<{ url: string }, unknown, {}> >; export interface Session { id: string; size: number; userCount: number; includesRequester: boolean; status: "SCHEDULED" | "OPEN" | "CLOSED" | "CANCELLED"; date: string; } export const getAllSessions = () => ( axios.get("/session", getJwtHeader()) as Promise> ).then((response) => response.data); export const joinSession = (sessionId: string) => ( axios.post("/session/join", { sessionId }, getJwtHeader()) as Promise< AxiosResponse > ).then((response) => response.data); export const leaveSession = (sessionId: string) => ( axios.post("/session/leave", { sessionId }, getJwtHeader()) as Promise< AxiosResponse > ).then((response) => response.data); export interface Tokens { available: number; purchased: number; consumed: number; used: number; } export const getAvailableTokenCount = () => (axios.get("/tokens", getJwtHeader()) as Promise>).then( (response) => response.data, ); export interface InvoiceSummary { purchaseData: { product: string; units: number; status: string; date: string; }[]; sessionsData: { date: string; status: string; }[]; } export const getInvoicingSummary = () => ( axios.get("/invoice", getJwtHeader()) as Promise< AxiosResponse > ).then((response) => response.data); export const openSession = (sessionId: string) => axios.post("/session/open", { sessionId }, getJwtHeader()); export const closeSession = (sessionId: string) => axios.post("/session/close", { sessionId }, getJwtHeader()); export const cancelSession = (sessionId: string) => axios.post("/session/cancel", { sessionId }, getJwtHeader()); export const createSession = (date: number, size: number) => axios.post("/session/create", { date, size }, getJwtHeader());