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

import com.iqser.red.service.persistence.management.v1.processor.entity.migration.SaasMigrationStatusEntity;
import com.iqser.red.service.persistence.service.v1.api.shared.model.dossiertemplate.dossier.file.SaasMigrationStatus;

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 java.util.List;

public interface SaasMigrationStatusRepository extends JpaRepository<SaasMigrationStatusEntity, String> {

    List<SaasMigrationStatusEntity> findAllByStatus(SaasMigrationStatus status);


    @Modifying
    @Query("update SaasMigrationStatusEntity e set e.status = :status where e.fileId = :fileId")
    void updateStatus(@Param("fileId") String fileId, @Param("status") SaasMigrationStatus status);


    @Modifying
    @Query("update SaasMigrationStatusEntity e set e.status = :status, e.errorCause = :errorCause where e.fileId = :fileId")
    void updateErrorStatus(@Param("fileId") String fileId, @Param("status") SaasMigrationStatus status, @Param("errorCause") String errorCause);


    @Modifying
    @Query("update SaasMigrationStatusEntity e set e.processingErrorCounter = :processingErrorCounter, e.errorCause = :errorCause where e.fileId = :fileId")
    void updateErrorCounter(@Param("fileId") String fileId, @Param("processingErrorCounter") Integer processingErrorCounter, @Param("errorCause") String errorCause);


    @Query("select count(*) from SaasMigrationStatusEntity e where e.status = :status")
    int countByStatus(@Param("status") SaasMigrationStatus status);


    @Query("select count(*) from SaasMigrationStatusEntity")
    int countAll();


    @Query("select count(*) from SaasMigrationStatusEntity e where e.status != 'FINISHED' and e.status != 'ERROR'")
    int findAllWhereStatusNotFinishedAndNotError();

}
