import { type FileCardType } from '@material-hu/components/design-system/FileCard/types';

import { SortingOrder } from 'src/pages/dashboard/Learning/common/types';
import { type RequestError } from 'src/types/services';
import { catchError } from 'src/utils/catchError';
import { signedUploadV2 } from 'src/utils/filesUtils';

import {
  CertificateAction,
  CertificateStatus,
  CertificatesSortColumn,
  LearningCertificateErrorCode,
  ListLearningCertificatesOrderBy,
} from '../constants';
import {
  type CertificateStatusAction,
  type CertificateStatusInfo,
  type CertificateStatusType,
  type LearningCertificateUsage,
  type ListLearningCertificatesOrderByValue,
  type ToBackendOrderByArgs,
} from '../types';

export const getCertificateStatusInfo = (
  status: CertificateStatusType,
): CertificateStatusInfo => {
  switch (status) {
    case CertificateStatus.ACTIVE:
      return { type: 'success', labelKey: 'general:active' };
    case CertificateStatus.INACTIVE:
      return { type: 'neutral', labelKey: 'general:inactive' };
  }
};

export const getCertificateActionFromStatus = (
  status: CertificateStatusType,
): CertificateStatusAction =>
  status === CertificateStatus.ACTIVE
    ? CertificateAction.ACTIVATE
    : CertificateAction.DEACTIVATE;

export const toBackendOrderBy = ({
  orderBy,
  order,
}: ToBackendOrderByArgs): ListLearningCertificatesOrderByValue | undefined => {
  if (orderBy !== CertificatesSortColumn.name) return undefined;

  if (order === SortingOrder.ASC)
    return ListLearningCertificatesOrderBy.NAME_ASC;
  if (order === SortingOrder.DESC)
    return ListLearningCertificatesOrderBy.NAME_DESC;

  return undefined;
};

/**
 * Uploads a certificate design image (signature, logo or custom background)
 * to S3 via the signed-upload flow. Resolves to a `FileCardType`: on success
 * it carries the resulting `fileAsset` (used to extract the `fileAssetId` /
 * `pictureId` for the payload); on failure it resolves to an `error` card so
 * the uploader renders the error state instead of throwing.
 */
export const uploadCertificateImage = async (
  file: File,
): Promise<FileCardType> => {
  const [error, fileAsset] = await catchError(signedUploadV2(file));
  if (error) return { status: 'error', file };
  return { status: 'success', file, fileAsset };
};

export const isLearningCertificateInUse = (usage: LearningCertificateUsage) =>
  usage.coursesCount + usage.learningPathsCount + usage.learningSessionsCount >
  0;

export const isLearningCertificateInUseError = (error: RequestError) =>
  error.response?.status === 409 &&
  error.response?.data?.code === LearningCertificateErrorCode.IN_USE;
