<?php

namespace App\Libs\Upload;

use App\Enums\AttachmentTypeEnum;
use App\Enums\DocumentTypeEnum;
use App\Exceptions\UploadFileException;
use App\Models\RealtimeMessage;
use App\Models\RealtimeMessageAttachment;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;

class UploadRealtimeMessageAttachments
{
   /**
    * Upload all realtime message attachment
    *
    * @param array $data
    * @param UploadedFile $uploadedFile
    * @return RealtimeMessage|null
    * @throws UploadFileException
    */
   public static function uploadAttachment(array $data, UploadedFile $uploadedFile): ?RealtimeMessage
   {
      DB::beginTransaction();

      try {
         $message = RealtimeMessage::createNewMessage($data);

         // Add attachment
         $basePath = sprintf(config('torryme.paths.docs'), $message->buildAttachmentDir());
         $filePath = upload_file_system(
            sprintf('%s_%s', DocumentTypeEnum::realtimeMessageAttachment->value, $message->{'uuid'}),
            $basePath,
            $uploadedFile,
         );

         if (filled($filePath)) {
            /** @var RealtimeMessageAttachment $attachment */
            $attachment = RealtimeMessageAttachment::store(array(
               'uuid' => generate_uuid('realtime_message_attachments'),
               'path' => $filePath,
               'original_name' => $uploadedFile->getClientOriginalName(),
               'attachment_type' => upload_file_type($uploadedFile),
               'realtime_message_id' => $message->{'id'},
            ));

            if ($attachment->{'attachment_type'}->{'value'} === AttachmentTypeEnum::video->{'value'}) {
               // Compute thumbnail video
               extract_video_thumbnail(
                  $attachment->buildAttachmentFilePath(),
                  replace_file_extension($filePath, config('torryme.constants.default_image_extension'))
               );
            }

            if ($attachment->{'attachment_type'}->{'value'} === AttachmentTypeEnum::image->{'value'}) {
               // Compute thumbnail image
               extract_video_thumbnail(
                  $attachment->buildAttachmentFilePath(),
                  replace_file_extension($filePath, config('torryme.constants.default_image_extension')),
                  "00:00:00.01"
               );
            }
         } else {
            throw new UploadFileException();
         }

         DB::commit();
         return $message->refresh();
      } catch (\Exception $exception) {
         DB::rollBack();
         log_debug($exception, 'UploadRealtimeMessageAttachments::uploadAttachment Unable to send media message');

         throw $exception;
      }
   }
}
