const TableImporter = require('./table-importer');
const {faker} = require('@faker-js/faker');
const {slugify} = require('@tryghost/string');

class RedirectsImporter extends TableImporter {
    static table = 'redirects';
    static dependencies = ['posts'];

    constructor(knex, transaction) {
        super(RedirectsImporter.table, knex, transaction);
    }

    async import(quantity) {
        const posts = await this.transaction
            .select('id', 'published_at')
            .from('posts')
            .where('type', 'post')
            .andWhere('status', 'published');

        this.quantity = quantity ? quantity / posts.length : 10;
        await this.importForEach(posts, this.quantity);
    }

    setReferencedModel(model) {
        this.model = model;

        // Reset the amount for each model
        this.amount = faker.number.int({
            min: 0,
            max: this.quantity
        });
    }

    generate() {
        if (this.amount <= 0) {
            return;
        }
        this.amount -= 1;
        return {
            id: this.fastFakeObjectId(),
            from: `/r/${faker.string.hexadecimal({length: 8, prefix: '', casing: 'lower'})}`,
            to: `${faker.internet.url()}/${slugify(`${faker.word.adjective()} ${faker.word.noun()}`).toLowerCase()}`,
            post_id: this.model.id,
            created_at: this.model.published_at,
            updated_at: this.model.published_at
        };
    }
}

module.exports = RedirectsImporter;
