use derive_builder::Builder;
use sqlx::query_as;
use uuid::Uuid;

use crate::{client::AppDbClient, cluster::Cluster, macros::with_id_query};

/// A workspace is 1:1 with a Postgres "database".
#[derive(Clone, Debug)]
pub struct Workspace {
    /// Primary key (defaults to UUIDv7).
    pub id: Uuid,

    /// Cluster housing the backing database for this workspace.
    pub cluster_id: Uuid,

    /// Postgres database name.
    pub db_name: String,

    /// Human friendly name for the workspace.
    pub display_name: String,

    /// ID of the user account that created this workspace.
    pub owner_id: Uuid,
}

impl Workspace {
    /// Build an insert statement to create a new workspace.
    pub fn insert<'a>() -> InsertBuilder<'a> {
        InsertBuilder::default()
    }

    pub async fn fetch_cluster(&self, app_db: &mut AppDbClient) -> sqlx::Result<Cluster> {
        Cluster::with_id(self.cluster_id).fetch_one(app_db).await
    }
}

with_id_query!(Workspace, sql = "select * from workspaces where id = $1");

#[derive(Builder, Clone, Copy, Debug)]
pub struct Insert<'a> {
    cluster_id: Uuid,
    db_name: &'a str,
    owner_id: Uuid,
}

impl<'a> Insert<'a> {
    pub async fn insert(self, app_db: &mut AppDbClient) -> sqlx::Result<Workspace> {
        query_as!(
            Workspace,
            "
insert into workspaces
(cluster_id, db_name, owner_id)
values ($1, $2, $3)
returning *
",
            self.cluster_id,
            self.db_name,
            self.owner_id
        )
        .fetch_one(&mut *app_db.conn)
        .await
    }
}
