import { DataTypes } from 'sequelize';
import { env } from '$env/dynamic/private';
import { building, dev } from '$app/environment';
import * as bcrypt from 'bcrypt';
import {
	BeforeCreate,
	BeforeUpdate,
	Column,
	Model,
	Sequelize,
	Table,
	Unique
} from 'sequelize-typescript';
import { Permissions } from '$lib/permissions';

@Table({ modelName: 'user' })
export class User extends Model {
	@Column({ type: DataTypes.STRING, allowNull: false })
	declare firstname: string;
	@Column({ type: DataTypes.STRING, allowNull: false })
	declare lastname: string;
	@Column({ type: DataTypes.DATE, allowNull: false })
	declare birthday: Date;
	@Column({ type: DataTypes.STRING })
	declare telephone: string;
	@Column({ type: DataTypes.STRING, allowNull: false })
	declare username: string;
	@Column({ type: DataTypes.ENUM('java', 'bedrock', 'cracked'), allowNull: false })
	declare playertype: 'java' | 'bedrock' | 'cracked';
	@Column({ type: DataTypes.STRING })
	declare password: string;
	@Column({ type: DataTypes.UUIDV4 })
	declare uuid: string;
}

@Table({ modelName: 'admin' })
export class Admin extends Model {
	@Column({ type: DataTypes.STRING, allowNull: false, unique: true })
	declare username: string;
	@Column({ type: DataTypes.STRING, allowNull: false })
	declare password: string;
	@Column({
		type: DataTypes.BIGINT,
		allowNull: false,
		get(this: Admin): Permissions | null {
			const permissions = this.getDataValue('permissions');
			return permissions != null ? new Permissions(permissions) : null;
		},
		set(this: Admin, value: Permissions) {
			this.setDataValue('permissions', value.value);
		}
	})
	declare permissions: Permissions;

	@BeforeCreate
	@BeforeUpdate
	static hashPassword(instance: Admin) {
		if ((instance.changed() || []).indexOf('password') != -1) {
			instance.password = bcrypt.hashSync(instance.password, 10);
		}
	}

	validatePassword(password: string): boolean {
		return bcrypt.compareSync(password, this.password);
	}
}

export const sequelize = new Sequelize(building ? 'sqlite::memory:' : env.DATABASE_URI, {
	// only log sql queries in dev mode
	logging: dev ? console.log : false,
	models: [User, Admin]
});
