use crate::repo::ChannelRepo;
use crate::model::space::Channel;
use sqlx::PgPool;

#[derive(Clone)]
pub struct ChannelRepository {
    pool: PgPool,
}

impl ChannelRepository {
    pub fn new(pool: PgPool) -> Self {
        Self { pool }
    }
}

#[rocket::async_trait]
impl ChannelRepo for ChannelRepository {
    async fn create(&self, name: &str, description: Option<&str>, space_id: i64) -> Result<i64, sqlx::Error> {
        let row = sqlx::query!(
            "INSERT INTO channels (name, description, space_id) VALUES ($1, $2, $3) RETURNING id",
            name,
            description,
            space_id
        )
        .fetch_one(&self.pool)
        .await?;
        Ok(row.id)
    }

    async fn get_by_space_id(&self, space_id: i64) -> Result<Vec<Channel>, sqlx::Error> {
        sqlx::query_as!(
            Channel,
            "SELECT id, name, description, space_id, created_at as \"created_at!\", updated_at as \"updated_at!\" FROM channels WHERE space_id = $1",
            space_id
        )
        .fetch_all(&self.pool)
        .await
    }
}
