// src/server/services/table_definition_service.rs
use tonic::{Request, Response, Status};
use common::proto::komp_ac::{
    common::Empty,
    table_definition::{
        table_definition_server::TableDefinition,
        PostTableDefinitionRequest, TableDefinitionResponse,
        ProfileTreeResponse, DeleteTableRequest, DeleteTableResponse,
    },
};
use sqlx::PgPool;
use crate::table_definition::handlers::{post_table_definition, get_profile_tree, delete_table};

#[derive(Debug)]
pub struct TableDefinitionService {
    pub db_pool: PgPool,
}

impl TableDefinitionService {
    pub fn new(db_pool: PgPool) -> Self {
        Self { db_pool }
    }
}

#[tonic::async_trait]
impl TableDefinition for TableDefinitionService {
    async fn post_table_definition(
        &self,
        request: Request<PostTableDefinitionRequest>,
    ) -> Result<Response<TableDefinitionResponse>, Status> {
        let response = post_table_definition(&self.db_pool, request.into_inner()).await?;
        Ok(Response::new(response))
    }

    async fn get_profile_tree(
        &self,
        request: Request<Empty>,
    ) -> Result<Response<ProfileTreeResponse>, Status> {
        get_profile_tree::get_profile_tree(&self.db_pool, request).await
    }

    async fn delete_table(
        &self,
        request: Request<DeleteTableRequest>,
    ) -> Result<Response<DeleteTableResponse>, Status> {
        let response = delete_table(&self.db_pool, request.into_inner()).await?;
        Ok(Response::new(response))
    }
}
