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

import { personalInformationUserPaths } from './types';

type Paths = (typeof personalInformationUserPaths)[number];

const schema = z.object({
    userId: z.string().trim().min(1).uuid(),
    actions: z
        .array(
            z.union([
                z.object({
                    op: z.enum(['add', 'replace']),
                    path: z.enum(personalInformationUserPaths),
                    value: z.string().min(1),
                }),
                z.object({
                    op: z.literal('remove'),
                    path: z.enum(personalInformationUserPaths),
                }),
            ])
        )
        .min(1),
});

export const updateUserPersonalInfo = async (
    client: Client,
    userId: string,
    actions: PatchAction<Paths>[]
): Promise<void> => {
    const result = schema.safeParse({ userId, actions });
    if (!result.success) {
        throw new TypeError('Invalid args', {
            cause: result.error.issues,
        });
    }

    await client
        .patch(`/boapi/proxy/user/fleets/${client.clientOptions.fleetId}/users/${userId}/pi`, actions, {
            headers: {
                'Content-Type': 'application/json-patch+json',
            },
        })
        .then(({ data }) => data);
};
