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

import { PersonalInformationUser, PersonalInformationUserType, personalInformationUserTypeSchema } from './types';

const searchTypes = ['email', 'username', 'phoneNumber'] as const;
export type SearchType = (typeof searchTypes)[number];
export type ResponseFind = {
    content: PersonalInformationUser[];
};

const querySchema = z.object({
    searchType: z.enum(searchTypes),
    searchQuery: z.string().min(1),
    types: z.array(personalInformationUserTypeSchema).min(1),
});

export const findUser = async (
    client: Client,
    searchType: SearchType,
    searchQuery: string,
    types: PersonalInformationUserType[]
): Promise<ResponseFind> => {
    const result = querySchema.safeParse({
        searchType,
        searchQuery,
        types,
    });

    if (!result.success) {
        throw new TypeError('Invalid arguments', {
            cause: result.error.issues,
        });
    }

    return client
        .post<ResponseFind>(
            `/boapi/proxy/user/fleets/${client.clientOptions.fleetId}/users/pi/find?types=${result.data.types.join(',')}`,
            {
                [result.data.searchType]: result.data.searchQuery,
            }
        )
        .then(({ data }) => data);
};
