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

import androidx.room.Dao
import androidx.room.Query
import com.manalejandro.odb2bluetooth.data.database.dto.VehicleDto
import com.manalejandro.odb2bluetooth.data.database.entities.Brand
import com.manalejandro.odb2bluetooth.data.database.entities.Model
import kotlinx.coroutines.flow.Flow

/**
 * Data Access Object for vehicle-related queries (brands and models)
 */
@Dao
interface VehicleDao {

    @Query("SELECT * FROM brands ORDER BY name")
    fun getAllBrands(): Flow<List<Brand>>

    @Query("SELECT * FROM models WHERE brand_id = :brandId ORDER BY name")
    fun getModelsByBrand(brandId: Int): Flow<List<Model>>

    @Query("""
        SELECT 
            m.id as modelId,
            b.name as brand,
            m.name as model,
            m.full_name as fullName,
            COUNT(DISTINCT g.id) as generationCount,
            COUNT(DISTINCT s.id) as signalCount
        FROM models m
        JOIN brands b ON m.brand_id = b.id
        LEFT JOIN generations g ON m.id = g.model_id
        LEFT JOIN obd_signals s ON m.id = s.model_id
        GROUP BY m.id, b.name, m.name, m.full_name
        ORDER BY b.name, m.name
    """)
    fun getAllVehicles(): Flow<List<VehicleDto>>

    @Query("""
        SELECT 
            m.id as modelId,
            b.name as brand,
            m.name as model,
            m.full_name as fullName,
            COUNT(DISTINCT g.id) as generationCount,
            COUNT(DISTINCT s.id) as signalCount
        FROM models m
        JOIN brands b ON m.brand_id = b.id
        LEFT JOIN generations g ON m.id = g.model_id
        LEFT JOIN obd_signals s ON m.id = s.model_id
        WHERE b.name LIKE '%' || :query || '%' 
           OR m.name LIKE '%' || :query || '%'
           OR m.full_name LIKE '%' || :query || '%'
        GROUP BY m.id, b.name, m.name, m.full_name
        ORDER BY b.name, m.name
    """)
    fun searchVehicles(query: String): Flow<List<VehicleDto>>
}

