import { getActiveClient } from '~/client/api/activeClient';
import { ingestInCache } from '~/cache/api/ingestInCache';
import { prepareMyInvitationsPayload } from '../utils/prepareMyInvitationsPayload';
import { invitationLinkedObject } from '~/utils/linkedObject/invitationLinkedObject';

/* begin_public_function
  id: invitation.get
*/
/**
 * ```js
 * import { getInvitation } from '@amityco/ts-sdk'
 * const { invitation } = await getInvitation(targetType, targetId)
 * ```
 *
 * Get a {@link Amity.Invitation} object
 *
 * @param targetType The type of the target of the {@link Amity.Invitation}
 * @param targetId The ID of the target of the {@link Amity.Invitation}
 * @returns A {@link Amity.Invitation} object
 *
 * @category Invitation API
 * @async
 */
export const getInvitation = async (
  targetType: Amity.Invitation['targetType'],
  targetId: Amity.Invitation['targetId'],
): Promise<Amity.Cached<Amity.Invitation | undefined>> => {
  const client = getActiveClient();
  client.log('invitation/getInvitation', targetType, targetId);

  const { data: payload } = await client.http.get<Amity.MyInvitationsPayload>(
    `/api/v1/invitations/me`,
    { params: { targetType, targetId } },
  );

  const data = prepareMyInvitationsPayload(payload);

  const cachedAt = client.cache && Date.now();

  if (client.cache) ingestInCache(data, { cachedAt });

  return {
    data: data.invitations[0] ? invitationLinkedObject(data.invitations[0]) : undefined,
    cachedAt,
  };
};
/* end_public_function */
