import { Client } from '@vulog/aima-client';
import { z } from 'zod';

import { Label } from './types';

const schema = z.object({
    userId: z.string().uuid(),
});

const schemaData = z.object({
    userId: z.string().uuid(),
    labelId: z.number().positive(),
});

export const getLabelsForUser = async (client: Client, userId: string) => {
    const result = schema.safeParse({ userId });
    if (!result.success) {
        throw new TypeError('Invalid args', {
            cause: result.error.issues,
        });
    }

    return client
        .get<Label[]>(`boapi/proxy/user/fleets/${client.clientOptions.fleetId}/users/${userId}/userLabels`)
        .then(({ data }) => data);
};

export const addLabelForUser = async (client: Client, userId: string, labelId: number) => {
    const result = schemaData.safeParse({ userId, labelId });
    if (!result.success) {
        throw new TypeError('Invalid args', {
            cause: result.error.issues,
        });
    }

    await client.post(`boapi/proxy/user/fleets/${client.clientOptions.fleetId}/users/${userId}/userLabels`, {
        labelId,
    });
};

export const removeLabelForUser = async (client: Client, userId: string, labelId: number) => {
    const result = schemaData.safeParse({ userId, labelId });
    if (!result.success) {
        throw new TypeError('Invalid args', {
            cause: result.error.issues,
        });
    }

    await client.delete(
        `boapi/proxy/user/fleets/${client.clientOptions.fleetId}/users/${userId}/userLabels/${labelId}`
    );
};
