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

//! Queries for `k_sol_launch_surface_keys`.

/// Inserts or updates one launch-surface matching key and returns its stable internal id.
pub async fn query_launch_surface_keys_upsert(
    database: &crate::Database,
    dto: &crate::LaunchSurfaceKeyDto,
) -> Result<i64, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query(
                r#"
INSERT INTO k_sol_launch_surface_keys (
    launch_surface_id,
    match_kind,
    match_value,
    created_at,
    updated_at
)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT(match_kind, match_value) DO UPDATE SET
    launch_surface_id = excluded.launch_surface_id,
    updated_at = excluded.updated_at
                "#,
            )
            .bind(dto.launch_surface_id)
            .bind(dto.match_kind.clone())
            .bind(dto.match_value.clone())
            .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_surface_keys on sqlite: {}",
                    error
                )));
            }
            let id_result = sqlx::query_scalar::<sqlx::Sqlite, i64>(
                r#"
SELECT id
FROM k_sol_launch_surface_keys
WHERE match_kind = ? AND match_value = ?
LIMIT 1
                "#,
            )
            .bind(dto.match_kind.clone())
            .bind(dto.match_value.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_surface_keys id for '{}:{}' on sqlite: {}",
                        dto.match_kind, dto.match_value, error
                    )));
                },
            }
        },
    }
}

/// Returns one launch-surface matching key identified by its kind and value, if it exists.
pub async fn query_launch_surface_keys_get_by_match(
    database: &crate::Database,
    match_kind: &str,
    match_value: &str,
) -> Result<std::option::Option<crate::LaunchSurfaceKeyDto>, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query_as::<sqlx::Sqlite, crate::LaunchSurfaceKeyEntity>(
                r#"
SELECT
    id,
    launch_surface_id,
    match_kind,
    match_value,
    created_at,
    updated_at
FROM k_sol_launch_surface_keys
WHERE match_kind = ? AND match_value = ?
LIMIT 1
                    "#,
            )
            .bind(match_kind)
            .bind(match_value)
            .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_surface_keys '{}:{}' on sqlite: {}",
                        match_kind, match_value, error
                    )));
                },
            };
            match entity_option {
                Some(entity) => return crate::LaunchSurfaceKeyDto::try_from(entity).map(Some),
                None => return Ok(None),
            }
        },
    }
}

/// Lists all launch-surface matching keys attached to one launch surface id.
pub async fn query_launch_surface_keys_list_by_surface_id(
    database: &crate::Database,
    launch_surface_id: i64,
) -> Result<std::vec::Vec<crate::LaunchSurfaceKeyDto>, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query_as::<sqlx::Sqlite, crate::LaunchSurfaceKeyEntity>(
                r#"
SELECT
    id,
    launch_surface_id,
    match_kind,
    match_value,
    created_at,
    updated_at
FROM k_sol_launch_surface_keys
WHERE launch_surface_id = ?
ORDER BY match_kind ASC, match_value ASC
                    "#,
            )
            .bind(launch_surface_id)
            .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_surface_keys by surface_id '{}' on sqlite: {}",
                        launch_surface_id, error
                    )));
                },
            };
            let mut dtos = std::vec::Vec::new();
            for entity in entities {
                let dto_result = crate::LaunchSurfaceKeyDto::try_from(entity);
                let dto = match dto_result {
                    Ok(dto) => dto,
                    Err(error) => return Err(error),
                };
                dtos.push(dto);
            }
            return Ok(dtos);
        },
    }
}
