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

import { ReferralInfo } from './types';

export const checkInvitationCode = async (client: Client, referralCode: string): Promise<ReferralInfo | undefined> => {
    const result = z.string().trim().min(1).safeParse(referralCode);
    if (!result.success) {
        throw new TypeError('Invalid referralCode', {
            cause: result.error.issues,
        });
    }

    return client
        .get<ReferralInfo>(`boapi/proxy/user/fleets/${client.clientOptions.fleetId}/invitation/check/${referralCode}`)
        .then(({ data }) => data)
        .catch((error: any) => {
            if (error.formattedError?.status === 404) {
                return undefined;
            }
            throw error;
        });
};
