const BASE_URL = "http://192.168.100.6:8080"; // TODO change this

async function post<T>(path: string, body: object): Promise<T> {
    const res = await fetch(`${BASE_URL}${path}`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
    });
    if (!res.ok) throw new Error(await res.text().catch(() => `HTTP ${res.status}`));
    return res.json();
}

async function get<T>(path: string, params?: Record<string, any>): Promise<T> {
    const url = new URL(`${BASE_URL}${path}`);
    if (params) {
        Object.entries(params).forEach(([k, v]) => {
            if (v !== undefined && v !== null) url.searchParams.set(k, String(v));
        });
    }
    const res = await fetch(url.toString());
    if (!res.ok) throw new Error(await res.text().catch(() => `HTTP ${res.status}`));
    return res.json();
}

export type LoginPayload    = { email: string; password: string };
export type RegisterPayload = { email: string; password: string;};
export type JwtResponse     = { token: string; email: string; message: string };
export type UserDTO         = { id: number; email: string; name?: string };

export type Subject = {
    id:   string;
    name: string;
};

export type Entry = {
    id:            string;
    title:         string;
    timePublished: string;
    groupName:     string;
    infoEntry:     string;
    paragraph:     string;
    filepath?:     string;
    subject:       Subject;
};

export type SpringPage<T> = {
    content:       T[];
    totalPages:    number;
    totalElements: number;
    last:          boolean;
    number:        number;
};


export const authApi = {
    login:    (p: LoginPayload)    => post<JwtResponse>("/login", p),
    register: (p: RegisterPayload) => post<UserDTO>("/register", p),
};


export const entriesApi = {
    getGroups: () =>
        get<string[]>("/groups"),

    getEntries: (params: { subjectId?: string; groupName?: string; page?: number }) =>
        get<SpringPage<Entry>>("/entries", params),

    getEntry: (id: string) =>
        get<Entry>(`/entries/${id}`),
};