package com.manalejandro.odb2bluetooth.data.database.dao

import androidx.room.Dao
import androidx.room.Query
import com.manalejandro.odb2bluetooth.data.database.dto.SignalDto
import com.manalejandro.odb2bluetooth.data.database.entities.ObdSignal
import kotlinx.coroutines.flow.Flow

/**
 * Data Access Object for OBD signals queries
 */
@Dao
interface ObdSignalDao {

    @Query("SELECT * FROM obd_signals WHERE model_id = :modelId ORDER BY signal_id")
    fun getSignalsByModel(modelId: Int): Flow<List<ObdSignal>>

    @Query("""
        SELECT 
            s.id,
            b.name as brand,
            m.name as model,
            s.signal_id as signalId,
            s.name as signalName,
            s.path,
            s.unit,
            s.header,
            s.command,
            s.frequency,
            s.description
        FROM obd_signals s
        JOIN models m ON s.model_id = m.id
        JOIN brands b ON m.brand_id = b.id
        WHERE s.model_id = :modelId
        ORDER BY s.signal_id
    """)
    fun getSignalsDtoByModel(modelId: Int): Flow<List<SignalDto>>

    @Query("SELECT * FROM obd_signals WHERE id = :signalId")
    suspend fun getSignalById(signalId: Int): ObdSignal?

    @Query("""
        SELECT * FROM obd_signals 
        WHERE model_id = :modelId 
        AND (name LIKE '%' || :query || '%' OR signal_id LIKE '%' || :query || '%')
        ORDER BY signal_id
    """)
    fun searchSignals(modelId: Int, query: String): Flow<List<ObdSignal>>
}

