use sqlx::{postgres::types::Oid, query_as};

use crate::{client::WorkspaceClient, pg_acl::PgAclItem};

#[derive(Clone, Debug)]
pub struct PgDatabase {
    /// Row identifier
    pub oid: Oid,
    /// Database name
    pub datname: String,
    /// Owner of the database, usually the user who created it
    pub datdba: Oid,
    /// Character encoding for this database (pg_encoding_to_char() can translate this number to the encoding name)
    pub encoding: i32,
    /// Locale provider for this database: b = builtin, c = libc, i = icu
    pub datlocprovider: i8,
    /// If true, then this database can be cloned by any user with CREATEDB privileges; if false, then only superusers or the owner of the database can clone it.
    pub datistemplate: bool,
    /// If false then no one can connect to this database. This is used to protect the template0 database from being altered.
    pub datallowconn: bool,
    /// Indicates that there are login event triggers defined for this database. This flag is used to avoid extra lookups on the pg_event_trigger table during each backend startup. This flag is used internally by PostgreSQL and should not be manually altered or read for monitoring purposes.
    pub dathasloginevt: bool,
    /// Sets maximum number of concurrent connections that can be made to this database. -1 means no limit, -2 indicates the database is invalid.
    pub datconnlimit: i32,
    /// The default tablespace for the database. Within this database, all tables for which pg_class.reltablespace is zero will be stored in this tablespace; in particular, all the non-shared system catalogs will be there.
    pub dattablespace: Oid,
    /// LC_COLLATE for this database
    pub datcollate: String,
    /// LC_CTYPE for this database
    pub datctype: String,
    /// Collation provider locale name for this database. If the provider is libc, datlocale is NULL; datcollate and datctype are used instead.
    pub datlocale: Option<String>,
    /// ICU collation rules for this database
    pub daticurules: Option<String>,
    /// Provider-specific version of the collation. This is recorded when the database is created and then checked when it is used, to detect changes in the collation definition that could lead to data corruption.
    pub datcollversion: Option<String>,
    /// Access privileges; see Section 5.8 for details
    pub datacl: Option<Vec<PgAclItem>>,
}

impl PgDatabase {
    pub fn current() -> CurrentQuery {
        CurrentQuery {}
    }
}

#[derive(Clone, Debug)]
pub struct CurrentQuery {}

impl CurrentQuery {
    pub async fn fetch_one(self, client: &mut WorkspaceClient) -> Result<PgDatabase, sqlx::Error> {
        query_as!(
            PgDatabase,
            r#"
select
    oid,
    datname,
    datdba,
    encoding,
    datlocprovider,
    datistemplate,
    datallowconn,
    dathasloginevt,
    datconnlimit,
    dattablespace,
    datcollate,
    datctype,
    datlocale,
    daticurules,
    datcollversion,
    datacl::text[] as "datacl: Vec<PgAclItem>"
from pg_database
where datname = current_database()
"#,
        )
        .fetch_one(client.get_conn())
        .await
    }
}
