import { of } from 'rxjs';
import { catchError, map, switchMap } from 'rxjs/operators';

import { gqlRequest, uploadS3 } from '@/modules/@common/request';

const queryGetLinksGQL = `
  query GetS3Links($filename: String!, $contentOwnerId: Float!, $fromLiveEvent: Boolean) {
    S3UploadLink(filename: $filename, contentOwnerId: $contentOwnerId, fromLiveEvent: $fromLiveEvent) {
      uploadUrl
      downloadUrl
    }
  }
`;

// need for create place in bucket
// not for validation
const TMP_BUCKET_KEY = 911111111119;

export const uploadFileAndGetDownloadUrl$ = ({ file }: { file: File; contentOwnerId: number }) => {
  const filename = file.name.replace(/\s/g, '_');
  const contentOwnerId = TMP_BUCKET_KEY;

  return gqlRequest({
    query: queryGetLinksGQL,
    variables: { filename, contentOwnerId, fromLiveEvent: true },
  }).pipe(
    switchMap(({ data, errors }) => {
      if (errors?.length || !data?.S3UploadLink) return of(null);
      const { uploadUrl, downloadUrl } = data.S3UploadLink;

      return uploadS3(uploadUrl, file).pipe(
        map((res) => (!res?.errors?.length ? downloadUrl : null)),
        catchError(() => of(null)),
      );
    }),
    catchError(() => of(null)),
  );
};
