import { Entity, ManyToOne, Property } from '@mikro-orm/core';
import { BaseEntity } from '../_BaseEntity';
import { User } from '../user/_User';
import { FastifyInstance } from 'fastify';
import { App } from '../app/_App';

interface CryptoMethods {
    encrypt(text: string): string;
    decrypt(text: string): string;
}

declare module 'fastify' {
    interface FastifyInstance extends CryptoMethods {}
}

@Entity()
export class Credential extends BaseEntity {
    @ManyToOne(() => User)
    user!: User;

    @ManyToOne(() => App)
    app!: App;

    @Property({ columnType: 'text', nullable: true })
    encryptedCredentials?: string;

    getDecryptedCredentials(): string | undefined {
        if (!this.encryptedCredentials) return undefined;
        return this.decrypt(this.encryptedCredentials);
    }

    setEncryptedCredentials(value: string): void {
        this.encryptedCredentials = this.encrypt(value);
    }

    private encrypt(text: string): string {
        return (this.constructor as typeof Credential).fastifyInstance.encrypt(text);
    }

    private decrypt(text: string): string {
        return (this.constructor as typeof Credential).fastifyInstance.decrypt(text);
    }

    static fastifyInstance: FastifyInstance;
}
