import { signedUploadV2 } from 'src/utils/filesUtils';

import {
  type CreateLearningSession,
  type NewSessionFormValues,
  type SessionConfiguration,
} from '../types';

export const formatSessionBasicInformation = async (
  formValues: NewSessionFormValues,
  formatDate: (date: Date, format: string) => string,
) => {
  const { coverPicture } = formValues.basic_information;
  const hasCoverPicture = Boolean(coverPicture?.url);

  let pictureId: number | null = null;

  if (!hasCoverPicture && coverPicture?.cropped) {
    const extension = coverPicture.cropped.type.split('/')[1];
    const newFileName = `${crypto.randomUUID()}.${extension}`;

    const pictureToUpload = new File([coverPicture.cropped], newFileName, {
      type: coverPicture.cropped.type,
    });

    const uploadedAsset = await signedUploadV2(pictureToUpload, false, false);
    pictureId = uploadedAsset.id;
  }

  let formattedLocalDate: string | undefined;
  let formattedStartTime: string | undefined;
  let formattedEndTime: string | undefined;

  if (formValues.basic_information.localDate) {
    formattedLocalDate = formatDate(
      formValues.basic_information.localDate,
      'yyyy-MM-dd',
    );
  }
  if (formValues.basic_information.startTime) {
    formattedStartTime = formatDate(
      formValues.basic_information.startTime,
      'HH:mm',
    );
  }
  if (formValues.basic_information.endTime) {
    formattedEndTime = formatDate(
      formValues.basic_information.endTime,
      'HH:mm',
    );
  }

  const formattedSession: Partial<CreateLearningSession> = {
    pictureId,
    title: formValues.basic_information.title,
    description: formValues.basic_information.description,
    timeZone: formValues.basic_information.timeZone,
    localDate: formattedLocalDate,
    startTime: formattedStartTime,
    endTime: formattedEndTime,
  };

  return formattedSession;
};

export const formatSessionConfiguration = (
  formValues: NewSessionFormValues,
) => {
  const { configuration } = formValues;

  const formattedConfiguration: SessionConfiguration = {
    type: configuration.type,
    sendNotification: configuration.sendNotification,
    address: configuration.address,
    meetingLink: configuration.meetingLink,
    collaborator: configuration.collaborator,
    isObligatory: configuration.isObligatory,
    issueCertificate: configuration.issueCertificate,
  };

  return formattedConfiguration;
};
