import { type PostData } from 'src/types/posts';
import { type LinkPreviewResponse } from 'src/types/previewLink';

export type ContentOnlyEditRequestPayload = {
  body: string;
  bodyHtml?: string;
  bodyAttributes: PostData['bodyAttributes'];
  linkPreviews: Record<string, LinkPreviewResponse>;
  taggedUserIds?: number[];
  // humand-main-api develop still validates this as required for group edit requests.
  attachments?: PostData['attachments'];
};

type ToContentOnlyEditRequestPayloadOptions = {
  includeRequiredGroupFields?: boolean;
};

const stripNullLinkPreviews = (
  linkPreviews: PostData['linkPreviews'],
): Record<string, LinkPreviewResponse> => {
  if (!linkPreviews) return {};
  return Object.fromEntries(
    Object.entries(linkPreviews).filter(
      (entry): entry is [string, LinkPreviewResponse] => entry[1] !== null,
    ),
  );
};

/**
 * Contract agreed with backend for `requestEdit` endpoints:
 * only post content can be updated (text + mentions + link previews).
 */
export const toContentOnlyEditRequestPayload = (
  postData: PostData,
  {
    includeRequiredGroupFields = false,
  }: ToContentOnlyEditRequestPayloadOptions = {},
): ContentOnlyEditRequestPayload => {
  const taggedUserIds = postData.taggedUserIds?.filter(
    (userId): userId is number => Number.isFinite(userId),
  );

  return {
    body: postData.body,
    bodyHtml: postData.bodyHtml,
    bodyAttributes: postData.bodyAttributes ?? [],
    linkPreviews: stripNullLinkPreviews(postData.linkPreviews),
    ...(includeRequiredGroupFields && { attachments: [] }),
    ...(taggedUserIds && taggedUserIds.length > 0 && { taggedUserIds }),
  };
};
