import {Model} from './Model';

export interface IMigration {
    id?: number;
    uuid: string;
    applied: boolean;
    offlineUpdatedAt?: string;
}

export class Migration extends Model<IMigration> implements IMigration {
    id?: number;
    uuid: string;
    applied: boolean;
    offlineUpdatedAt?: string;

    public static getTableName() {
        return 'migrations';
    }

    public static getSchema() {
        return '++id, uuid, applied, offlineUpdatedAt';
    }

    constructor(uuid: string, applied: boolean, offlineUpdatedAt?: string, id?: number) {
        super();

        this.uuid = uuid;
        this.applied = applied;

        if ( typeof offlineUpdatedAt !== 'undefined' ) {
            this.offlineUpdatedAt = offlineUpdatedAt;
        }

        if ( id ) {
            this.id = id;
        }
    }

    public getSaveRecord(): any {
        return {
            ...(this.id ? { id: this.id } : {}),
            uuid: this.uuid,
            applied: this.applied,
            ...(typeof this.offlineUpdatedAt === 'undefined' ? {} : { offlineUpdatedAt: this.offlineUpdatedAt }),
        };
    }

    public getDatabase(): Dexie.Table<IMigration, number> {
        return this.staticClass().dbService.table('migrations') as Dexie.Table<IMigration, number>;
    }
}
