import { ConfigService } from '@nestjs/config';

const DEFAULT_SHARE_BASE_URL = 'https://oudelaa.com';

export const normalizeShareBaseUrl = (value: string | undefined | null): string =>
  (value?.trim() || DEFAULT_SHARE_BASE_URL).replace(/\/+$/, '');

export const resolveShareBaseUrl = (configService?: ConfigService): string => {
  const configured =
    process.env.SHARE_BASE_URL?.trim() ||
    process.env.PUBLIC_WEB_URL?.trim() ||
    configService?.get<string>('shareBaseUrl', { infer: true }) ||
    configService?.get<string>('publicWebUrl', { infer: true }) ||
    '';

  return normalizeShareBaseUrl(configured);
};

export const buildProfileShareUrl = (
  baseUrl: string,
  user: { id?: unknown; _id?: unknown; username?: unknown },
): string => {
  const username = typeof user.username === 'string' ? user.username.trim() : '';
  if (username) {
    return `${baseUrl}/u/${encodeURIComponent(username)}`;
  }

  const candidate = user.id ?? user._id;
  const userId = candidate?.toString?.() ?? String(candidate ?? '');
  return `${baseUrl}/profile/${encodeURIComponent(userId)}`;
};

export const buildPostShareUrl = (baseUrl: string, postId: string): string =>
  `${baseUrl}/posts/${encodeURIComponent(postId)}`;

export const buildAiMusicShareUrl = (baseUrl: string, archiveItemId: string): string =>
  `${baseUrl}/ai/music/${encodeURIComponent(archiveItemId)}`;
