use argon2::password_hash::rand_core::OsRng;
use argon2::password_hash::SaltString;
use argon2::Argon2;
use argon2::PasswordHasher;
use sea_orm_migration::prelude::*;

#[derive(DeriveMigrationName)]
pub struct Migration;

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        let argon2 = Argon2::default();
        let salt = SaltString::generate(OsRng);
        let hash = argon2
            .hash_password("admin".as_bytes(), &salt)
            .expect("Generating Admin Password Hash failed");
        let insert = Query::insert()
            .into_table(User::Table)
            .columns([User::Name, User::Email, User::Hash])
            .values_panic(["admin".into(), "admin".into(), hash.to_string().into()])
            .to_owned();

        manager.exec_stmt(insert).await?;
        Ok(())
    }

    async fn down(&self, _manager: &SchemaManager) -> Result<(), DbErr> {
        Ok(())
    }
}

#[derive(DeriveIden)]
enum User {
    Table,
    Name,
    Email,
    Hash,
}
