import { $t } from '#/locales';

interface UploadResponseData {
  path?: string;
}

interface UploadResponseBody {
  data?: UploadResponseData;
  errorCode?: number;
  message?: string;
}

function getMessageFromUnknown(error: unknown) {
  if (typeof error === 'string' && error) {
    return error;
  }

  if (!error || typeof error !== 'object') {
    return '';
  }

  const raw = error as {
    message?: unknown;
    response?: unknown;
  };

  if (typeof raw.message === 'string' && raw.message) {
    return raw.message;
  }

  if (typeof raw.response === 'string' && raw.response) {
    try {
      const parsed = JSON.parse(raw.response) as UploadResponseBody;
      return parsed.message || '';
    } catch {
      return raw.response;
    }
  }

  return '';
}

export function normalizeUploadError(error: unknown) {
  const message = getMessageFromUnknown(error);
  return new Error(message || $t('cropper.message.uploadFailed'));
}

export function resolveUploadPath(response: UploadResponseBody) {
  if (!response || response.errorCode !== 0) {
    throw new Error(response?.message || $t('cropper.message.uploadFailed'));
  }

  const path = response.data?.path;
  if (!path) {
    throw new Error($t('cropper.message.notUrl'));
  }

  return path;
}
