import { generateToken } from "@autoplex/utils";
import { Entity, PrimaryGeneratedColumn, Column, BaseEntity } from "typeorm";

@Entity()
export class RegisterToken extends BaseEntity
{
	@PrimaryGeneratedColumn()
	id!: number;

	@Column()
	token!: string

	/**
	 * Check if the provided token is valid
	 */
	public static async isValid(token: string) {
		if (typeof token !== "string") {
			return false;
		}
		return Boolean(token) && await RegisterToken.count({token}) > 0;
	}

	/**
	 * Create a new registration token and insert it into the database
	 */
	public static async generate() {
		let token = new RegisterToken();
		token.token = await generateToken();
		return await token.save();
	}
}
