use diesel::prelude::*;
use serde::{Serialize, Deserialize};
use siren::ServiceError;

use crate::storage::{schema::guilds, connection};

#[derive(Queryable, QueryableByName, Serialize, Deserialize)]
#[diesel(table_name = guilds)]
pub struct QueryGuild {
  pub id: i64,
  pub bot_id: i64,
  pub volume: i32
}

impl QueryGuild {
  pub fn get(id: i64) -> Result<Self, ServiceError> {
    let mut conn = connection()?;
    let guild = guilds::table.filter(guilds::id.eq(id)).first(&mut conn)?;
    Ok(guild)
  }
}

#[derive(Insertable, AsChangeset, Serialize, Deserialize)]
#[diesel(table_name = guilds)]
pub struct InsertGuild {
  pub id: i64,
  pub bot_id: i64,
  pub volume: i32
}

impl InsertGuild {
  pub fn insert(guild: Self) -> Result<QueryGuild, ServiceError> {
    let mut conn = connection()?;
    let guild = diesel::insert_into(guilds::table).values(guild).get_result(&mut conn)?;
    Ok(guild)
  }

  pub fn update_audio(id: i64, volume: i32) -> Result<QueryGuild, ServiceError> {
    let mut conn = connection()?;
    let guild = diesel::update(guilds::table.filter(guilds::id.eq(id))).set(guilds::volume.eq(volume)).get_result(&mut conn)?;
    Ok(guild)
  }
}
