// src/tables_data/handlers/get_table_data_by_position.rs
use tonic::Status;
use sqlx::PgPool;
use common::proto::komp_ac::tables_data::{
    GetTableDataByPositionRequest, GetTableDataRequest, GetTableDataResponse
};
use super::get_table_data;
use crate::shared::schema_qualifier::qualify_table_name_for_data; // Import schema qualifier

pub async fn get_table_data_by_position(
    db_pool: &PgPool,
    request: GetTableDataByPositionRequest,
) -> Result<GetTableDataResponse, Status> {
    let profile_name = request.profile_name;
    let table_name = request.table_name;

    if request.position < 1 {
        return Err(Status::invalid_argument("Position must be at least 1"));
    }

    let schema = sqlx::query!(
        "SELECT id FROM schemas WHERE name = $1",
        profile_name
    )
    .fetch_optional(db_pool)
    .await
    .map_err(|e| Status::internal(format!("Profile lookup error: {}", e)))?;

    let schema_id = schema.ok_or_else(|| Status::not_found("Profile not found"))?.id;

    let table_exists = sqlx::query_scalar!(
        r#"SELECT EXISTS(
            SELECT 1 FROM table_definitions
            WHERE schema_id = $1 AND table_name = $2
        ) AS "exists!""#,
        schema_id,
        table_name
    )
    .fetch_one(db_pool)
    .await
    .map_err(|e| Status::internal(format!("Table verification error: {}", e)))?;

    if !table_exists {
        return Err(Status::not_found("Table not found"));
    }

    // Qualify table name with schema
    let qualified_table = qualify_table_name_for_data(
        db_pool,
        &profile_name,
        &table_name,
    )
    .await?;

    let id_result = sqlx::query_scalar(
        &format!(
            r#"SELECT id FROM {}
            WHERE deleted = FALSE
            ORDER BY id ASC
            OFFSET $1
            LIMIT 1"#,
            qualified_table
        )
    )
    .bind(request.position - 1)
    .fetch_optional(db_pool)
    .await;

    let id: i64 = match id_result {
        Ok(Some(id)) => id,
        Ok(None) => return Err(Status::not_found("Position out of bounds")),
        Err(e) => {
            // Handle "relation does not exist" error specifically
            if let Some(db_err) = e.as_database_error() {
                if db_err.code() == Some(std::borrow::Cow::Borrowed("42P01")) {
                    return Err(Status::internal(format!(
                        "Table '{}' is defined but does not physically exist in the database as {}",
                        table_name, qualified_table
                    )));
                }
            }
            return Err(Status::internal(format!("Position query failed: {}", e)));
        }
    };

    get_table_data(
        db_pool,
        GetTableDataRequest {
            profile_name,
            table_name,
            id,
        }
    ).await
}
