// file: kb_lib/src/db/queries/launch_surface.rs

//! Queries for `k_sol_launch_surfaces`.

/// Inserts or updates one launch surface row and returns its stable internal id.
pub async fn query_launch_surfaces_upsert(
    database: &crate::Database,
    dto: &crate::LaunchSurfaceDto,
) -> Result<i64, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query(
                r#"
INSERT INTO k_sol_launch_surfaces (
    code,
    name,
    protocol_family,
    is_enabled,
    created_at,
    updated_at
)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(code) DO UPDATE SET
    name = excluded.name,
    protocol_family = excluded.protocol_family,
    is_enabled = excluded.is_enabled,
    updated_at = excluded.updated_at
                "#,
            )
            .bind(dto.code.clone())
            .bind(dto.name.clone())
            .bind(dto.protocol_family.clone())
            .bind(if dto.is_enabled { 1_i64 } else { 0_i64 })
            .bind(dto.created_at.to_rfc3339())
            .bind(dto.updated_at.to_rfc3339())
            .execute(pool)
            .await;
            if let Err(error) = query_result {
                return Err(crate::Error::Db(format!(
                    "cannot upsert k_sol_launch_surfaces on sqlite: {}",
                    error
                )));
            }
            let id_result = sqlx::query_scalar::<sqlx::Sqlite, i64>(
                r#"
SELECT id
FROM k_sol_launch_surfaces
WHERE code = ?
LIMIT 1
                "#,
            )
            .bind(dto.code.clone())
            .fetch_one(pool)
            .await;
            match id_result {
                Ok(id) => return Ok(id),
                Err(error) => {
                    return Err(crate::Error::Db(format!(
                        "cannot fetch k_sol_launch_surfaces id for code '{}' on sqlite: {}",
                        dto.code, error
                    )));
                },
            }
        },
    }
}

/// Returns one launch surface identified by its stable short code, if it exists.
pub async fn query_launch_surfaces_get_by_code(
    database: &crate::Database,
    code: &str,
) -> Result<std::option::Option<crate::LaunchSurfaceDto>, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query_as::<sqlx::Sqlite, crate::LaunchSurfaceEntity>(
                r#"
SELECT
    id,
    code,
    name,
    protocol_family,
    is_enabled,
    created_at,
    updated_at
FROM k_sol_launch_surfaces
WHERE code = ?
LIMIT 1
                    "#,
            )
            .bind(code)
            .fetch_optional(pool)
            .await;
            let entity_option = match query_result {
                Ok(entity_option) => entity_option,
                Err(error) => {
                    return Err(crate::Error::Db(format!(
                        "cannot read k_sol_launch_surfaces '{}' on sqlite: {}",
                        code, error
                    )));
                },
            };
            match entity_option {
                Some(entity) => return crate::LaunchSurfaceDto::try_from(entity).map(Some),
                None => return Ok(None),
            }
        },
    }
}

/// Lists all persisted launch surfaces ordered by code.
pub async fn query_launch_surfaces_list(
    database: &crate::Database,
) -> Result<std::vec::Vec<crate::LaunchSurfaceDto>, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query_as::<sqlx::Sqlite, crate::LaunchSurfaceEntity>(
                r#"
SELECT
    id,
    code,
    name,
    protocol_family,
    is_enabled,
    created_at,
    updated_at
FROM k_sol_launch_surfaces
ORDER BY code ASC
                    "#,
            )
            .fetch_all(pool)
            .await;
            let entities = match query_result {
                Ok(entities) => entities,
                Err(error) => {
                    return Err(crate::Error::Db(format!(
                        "cannot list k_sol_launch_surfaces on sqlite: {}",
                        error
                    )));
                },
            };
            let mut dtos = std::vec::Vec::new();
            for entity in entities {
                let dto_result = crate::LaunchSurfaceDto::try_from(entity);
                let dto = match dto_result {
                    Ok(dto) => dto,
                    Err(error) => return Err(error),
                };
                dtos.push(dto);
            }
            return Ok(dtos);
        },
    }
}
