import { ImageObject } from '@/types/Common';

const MEDIA_BASE = process.env.NEXT_PUBLIC_MEDIA_URL || '';

const getFolderById = (id: string | number) => Math.floor(Number(id) / 1000);

export type ImageSize = 'w64' | 'w256' | 'w640' | 'w1024' | 'w1920' | 'h256';

export type PossibleCreatorAvatarSizes = 64 | 256;

export const CREATOR_AVATAR_PLACEHOLDER = '/assets/images/user_avatar_placeholder_square.png';

export const buildMediaUrl = (id: string | number, size: ImageSize) =>
  `${MEDIA_BASE}/media_sizes/${getFolderById(id)}/${id}/${size}.webp`;

export const buildCroppedMediaUrl = (id: string | number, fileName: string) => {
  const extension = fileName.match(/\.([^.]+)$/)?.[1] || 'jpg';

  return `${MEDIA_BASE}/media_sizes/${getFolderById(id)}/${id}/crop.${extension}`;
};

export const getCreatorAvatarSrc = (
  imageId: number | null | undefined,
  size: Extract<ImageSize, 'w64' | 'w256'> = 'w256'
) => {
  if (imageId && Number.isFinite(imageId)) {
    return buildMediaUrl(imageId, size);
  }

  return CREATOR_AVATAR_PLACEHOLDER;
};

export type ImageMetaLabels = {
  source: string;
  photo: string;
  rightsHolder: string;
};

const DEFAULT_IMAGE_META_LABELS: ImageMetaLabels = {
  source: 'Kép forrása',
  photo: 'Fotó',
  rightsHolder: 'Jogtulajdonos',
};

export function buildImageMetaText(
  image: ImageObject,
  includeCaption: boolean = true,
  labels: ImageMetaLabels = DEFAULT_IMAGE_META_LABELS
): string | undefined {
  if (!image) return undefined;
  const parts: string[] = [];
  const caption = image.kepalairas?.trim();
  if (includeCaption && caption && caption.length > 0) parts.push(caption);
  const items: Array<{ label: string; value: unknown }> = [
    { label: labels.source, value: image.kepforrasa },
    { label: labels.photo, value: image.kepkeszitoje },
    { label: labels.rightsHolder, value: image.jogtulajdonos },
  ];
  items.forEach((i) => {
    const value = i.value != null ? String(i.value).trim() : '';
    if (value.length > 0) parts.push(`${i.label}: ${value}`);
  });
  return parts.length > 0 ? parts.join(', ') : undefined;
}
