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

const paths = ['/phoneNumber', '/email'] as const;
type Paths = (typeof paths)[number];

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

export const updateProfilePersonalInfo = async (
    client: Client,
    userId: string,
    profileId: string,
    actions: PatchAction<Paths>[]
): Promise<void> => {
    const result = schema.safeParse({ userId, profileId, 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}/profiles/${profileId}/pi`,
        actions,
        {
            headers: {
                'Content-Type': 'application/json-patch+json',
            },
        }
    );
};
