import { derived } from "svelte/store";
import { fetchWithToken, tokenStore } from "./repo";
import { PagedAutidLogSchema } from "@components/types/auditlog";

export class AuditLogRepo {
    async get(
        actionText: string | undefined,
        serverText: string | undefined,
        fullText: string | undefined,
        actor: number[] | undefined,
        actionType: string[] | undefined,
        timeFrom: number | undefined,
        timeTo: number | undefined,
        serverOwner: number[] | undefined,
        velocity: boolean | undefined,
        page: number,
        pageSize: number,
        sorting: string | undefined
    ) {
        const params = new URLSearchParams();
        if (actionText) params.append("actionText", actionText);
        if (serverText) params.append("serverText", serverText);
        if (fullText) params.append("fullText", fullText);
        if (actor) actor.forEach((a) => params.append("actor", a.toString()));
        if (actionType) actionType.forEach((a) => params.append("actionType", a));
        if (timeFrom) params.append("timeGreater", timeFrom.toString());
        if (timeTo) params.append("timeLess", timeTo.toString());
        if (serverOwner) serverOwner.forEach((s) => params.append("serverOwner", s.toString()));
        if (velocity !== undefined) params.append("velocity", velocity.toString());
        params.append("page", page.toString());
        params.append("limit", pageSize.toString());
        if (sorting) params.append("sorting", sorting);

        return await fetchWithToken("", `/auditlog?${params.toString()}`)
            .then((value) => value.json())
            .then((data) => PagedAutidLogSchema.parse(data));
    }
}

export const auditLog = derived(tokenStore, ($token) => new AuditLogRepo());
