import type {Perms, UserPerms} from "../types/perms.js";
import {fetchWithToken} from "./repo.js";
import {PermsSchema, UserPermsSchema} from "../types/perms.js";

export class PermsRepo {
    constructor(private token: string) {}

    public async listPerms(): Promise<Perms> {
        const res = await fetchWithToken(this.token, "/perms");

        if (res.ok) {
            return PermsSchema.parse(await res.json());
        } else {
            throw new Error("Could not fetch perms: " + res.statusText);
        }
    }

    public async getPerms(userId: number): Promise<UserPerms> {
        return await fetchWithToken(this.token, `/perms/user/${userId}`).then(value => value.json()).then(UserPermsSchema.parse);
    }

    public async setPrefix(userId: number, prefix: string): Promise<void> {
        const res = await fetchWithToken(this.token, `/perms/user/${userId}/prefix/${prefix}`, {
            method: "PUT",
        });

        if (!res.ok) {
            throw new Error("Could not set prefix: " + res.statusText);
        }
    }

    public async addPerm(userId: number, perm: string): Promise<void> {
        const res = await fetchWithToken(this.token, `/perms/user/${userId}/${perm}`, {
            method: "PUT",
        });

        if (!res.ok) {
            throw new Error("Could not add perm: " + res.statusText);
        }
    }

    public async removePerm(userId: number, perm: string): Promise<void> {
        const res = await fetchWithToken(this.token, `/perms/user/${userId}/${perm}`, {
            method: "DELETE",
        });

        if (!res.ok) {
            throw new Error("Could not remove perm: " + res.statusText);
        }
    }
}
