package com.ffii.fpsms.modules.master.entity

import com.ffii.fpsms.modules.master.entity.projections.ShopAndTruck
import com.ffii.core.support.AbstractRepository
import com.ffii.fpsms.modules.master.entity.projections.ShopCombo
import com.ffii.fpsms.modules.master.enums.ShopType
import com.ffii.fpsms.modules.pickOrder.entity.Truck
import org.springframework.data.jpa.repository.Query
import org.springframework.data.repository.query.Param
import org.springframework.stereotype.Repository

@Repository
interface ShopRepository : AbstractRepository<Shop, Long> {
    fun findAllByDeletedIsFalse(): List<Shop>

    fun findByIdAndDeletedIsFalse(id: Long): Shop?

    fun findByM18IdAndTypeAndDeletedIsFalse(m18Id: Long, type: ShopType): Shop?

    @Query(
        nativeQuery = true,
        value = "select s.m18Id from shop s where s.code regexp ?1 and s.type = ?2 and s.deleted = false")
    fun findM18IdsByCodeRegexpAndTypeAndDeletedIsFalse(codeRegexp: String, type: String): List<Long>?

    @Query(
        nativeQuery = true,
        value = "select s.m18Id from Shop s where s.code not regexp ?1 and s.type = ?2 and s.deleted = false")
    fun findM18IdsByCodeNotRegexpAndTypeAndDeletedIsFalse(codeNotRegexp: String, type: String): List<Long>?

    fun findShopComboByTypeAndDeletedIsFalse(type: ShopType): List<ShopCombo>

    fun findByCode(code: String): Shop?

    @Query(
        """
        SELECT s FROM Shop s
        WHERE s.deleted = false
          AND s.code IN :codes
        """
    )
    fun findAllByCodeInAndDeletedIsFalse(@Param("codes") codes: Collection<String>): List<Shop>

    @Query(
        nativeQuery = true,
        value = """
        SELECT s.id, s.code, s.name, s.contactNo, s.contactEmail, s.contactName, s.addr1, s.addr2, s.addr3, s.type, t.TruckLanceCode, t.DepartureTime as departureTime, t.LoadingSequence, t.districtReference, t.Store_id as Store_id, t.remark
        FROM shop s LEFT JOIN truck t ON s.id = t.shopId
        WHERE s.type = 'shop'
          AND s.deleted = false;
    """
    )
    fun findAllByTypeAndDeletedIsFalse(): List<ShopAndTruck>?

}
