// User.ts
import {
    Entity,
    Property,
    ManyToMany,
    Collection,
    OneToMany,
    BeforeCreate,
    BeforeUpdate,
    Unique,
} from '@mikro-orm/core';
import bcrypt from 'bcrypt';
import { BaseEntity } from '../_BaseEntity';
import { TenantApp } from '../tenant/TenantApps';
import { UserRole } from './UserRole';
import { Credential } from '../credentials/_Credential';

@Entity()
export class User extends BaseEntity {
    @Property()
    @Unique()
    username!: string;

    @Property({ hidden: true })
    password!: string;

    @Property()
    email!: string;

    @ManyToMany(() => UserRole, (role) => role.users, { owner: true })
    roles = new Collection<UserRole>(this);

    @OneToMany(() => TenantApp, (tenantApp) => tenantApp.user)
    tenantApps = new Collection<TenantApp>(this);

    @OneToMany(() => Credential, (credential) => credential.user)
    credentials = new Collection<Credential>(this);

    @BeforeCreate()
    @BeforeUpdate()
    async hashPassword() {
        if (this.password && !this.password.startsWith('$2b$')) {
            this.password = await bcrypt.hash(this.password, 12);
        }
    }
}
