package com.iqser.red.service.persistence.management.v1.processor.service.persistence.repository;

import java.time.OffsetDateTime;
import java.util.List;
import java.util.Optional;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import com.iqser.red.service.persistence.management.v1.processor.entity.download.DownloadStatusEntity;
import com.iqser.red.service.persistence.service.v1.api.shared.model.download.DownloadStatusValue;

public interface DownloadStatusRepository extends JpaRepository<DownloadStatusEntity, String> {

    List<DownloadStatusEntity> findAllByUserId(String userId);

    // The real id is currently the storageId, this is a quick fix fpr the new customer api
    // because i have no time to rewrite the complete logic that uses the storageId everywhere.
    Optional<DownloadStatusEntity> findByUuid(String uuid);

    @Modifying
    @Query("update DownloadStatusEntity ds set ds.status = :status where ds.storageId = :storageId")
    int updateStatus(@Param("storageId") String storageId, @Param("status") DownloadStatusValue status);


    @Modifying
    @Query("update DownloadStatusEntity ds set ds.status = :status, ds.errorCause = :errorCause where ds.storageId = :storageId")
    int updateStatusAndErrorCause(@Param("storageId") String storageId, @Param("status") DownloadStatusValue status, @Param("errorCause") String errorCause);


    @Modifying
    @Transactional
    @Query("update DownloadStatusEntity ds set ds.status = :status where ds.storageId = :storageId and ds.status != :status")
    int updateStatusOnlyIfNotAlreadySet(@Param("storageId") String storageId, @Param("status") DownloadStatusValue status);


    @Modifying
    @Query("update DownloadStatusEntity ds set ds.lastDownload = :lastDownload where ds.storageId = :storageId")
    void updateLastDownload(@Param("storageId") String storageId, @Param("lastDownload") OffsetDateTime lastDownload);

}
