use crate::commons::utils::CONFIG as config;
use crate::db::models::*;
use serde_json::{Value, json};

#[derive(Debug)]
pub struct Manager {
    pub id: i32,
    pub username: String,
    pub password: String,
    pub token: String,
}

pub enum ManagerLogin {
    /// username / password
    user(String, String),
    token(String),
}

impl Manager {
    pub async fn Login(m: ManagerLogin) -> Result<Self, String> {
        let Some(_) = &config.db else {
            println!("没有配置数据库, return Self;");
            return Ok(Manager {
                id: 1,
                username: "admin".to_string(),
                password: "123456".to_string(),
                token: "88236aeb-8d3f-6d56-fdf5-3adca3961df1".to_string(),
            });
        };
        match m {
            ManagerLogin::user(username, password) => {
                let rows = crate::db::db_query(
                    r#"select id,username,password,token from tb_manager where username=? and password=? limit 1;"#,
                    vec![json!(username), json!(password)],
                )
                .await
                .map_err(|err| format!("用户名或密码错误,{err}"))?;
                let row = rows.first().ok_or_else(|| "用户名或密码错误".to_string())?;

                Ok(Self {
                    id: get_i32(row, "id")?,
                    username: get_string(row, "username")?,
                    password: get_string(row, "password")?,
                    token: get_string(row, "token")?,
                })
            }
            ManagerLogin::token(token) => {
                let rows = crate::db::db_query(
                    r#"select id,username,password,token from tb_manager where token=? limit 1;"#,
                    vec![json!(token)],
                )
                .await
                .map_err(|err| format!("token异常,{err}"))?;
                let row = rows.first().ok_or_else(|| "token异常".to_string())?;
                Ok(Self {
                    id: get_i32(row, "id")?,
                    username: get_string(row, "username")?,
                    password: get_string(row, "password")?,
                    token: get_string(row, "token")?,
                })
            }
        }
    }
}
