import { Platform } from 'react-native';
import { getActiveClient } from './activeClient';
import { getDeviceId } from '~/core/device';
import { ASCApiError, ASCInvalidParameterError } from '~/core/errors';

export const registerPushNotification = async (deviceToken: string): Promise<boolean> => {
  const client = getActiveClient();

  let platform: 'ios' | 'android';

  if (Platform.OS === 'ios' || Platform.OS === 'android') {
    platform = Platform.OS;
  } else {
    throw new ASCInvalidParameterError('Unsupported platform');
  }

  const deviceId = await getDeviceId();

  const {
    data: { status, error },
  } = await client.http.post<{ status: 'success' | 'error'; error?: string }>(
    '/v1/notification',
    {
      userId: client.userId,
      deviceId,
      platform,
      token: deviceToken,
    },
    { headers: { 'X-API-Key': client.apiKey } },
  );

  if (error) {
    throw new ASCApiError(error, Amity.ServerError.BUSINESS_ERROR, Amity.ErrorLevel.ERROR);
  }

  return status === 'success';
};
