use chrono::{NaiveDateTime, TimeDelta};
use sqlx::{query_as, PgPool};

use crate::utils::token_generation::generate_token_and_expiration;

#[derive(Debug)]
pub struct Registration {
    pub id: i32,
    pub token: String,
    pub userid: i32,
    pub expires: NaiveDateTime,
}

use super::{password_reset::Token, Result};

impl Registration {
    pub async fn insert_new_for_user(pool: &PgPool, user_id: i32) -> Result<Registration> {
        let (token, expires) = generate_token_and_expiration(64, TimeDelta::hours(24));

        let inserted = query_as!(
            Registration,
            "INSERT INTO registration (token, userId, expires) VALUES ($1, $2, $3) RETURNING *;",
            token,
            user_id,
            expires
        )
        .fetch_one(pool)
        .await?;

        Ok(inserted)
    }

    pub async fn does_token_exist(pool: &PgPool, token: &str) -> Result<Option<Registration>> {
        query_as!(
            Registration,
            "SELECT * FROM registration WHERE token = $1 AND expires > NOW();",
            token
        )
        .fetch_optional(pool)
        .await
    }

    pub async fn delete(pool: &PgPool, token: &str) -> Result<()> {
        sqlx::query!("DELETE FROM registration WHERE token = $1;", token)
            .execute(pool)
            .await?;

        Ok(())
    }
}

impl Token for Registration {
    async fn delete(&self, pool: &PgPool) -> Result<()> {
        Registration::delete(pool, &self.token).await
    }
}
