"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FeatureLifecycleStore = void 0;
class FeatureLifecycleStore {
    constructor(db) {
        this.db = db;
    }
    async insert(featureLifecycleStages) {
        const joinedLifecycleStages = featureLifecycleStages
            .map((stage) => `('${stage.feature}', '${stage.stage}')`)
            .join(', ');
        const query = this.db
            .with('new_stages', this.db.raw(`
                    SELECT v.feature, v.stage
                    FROM (VALUES ${joinedLifecycleStages}) AS v(feature, stage)
                    JOIN features ON features.name = v.feature
                    LEFT JOIN feature_lifecycles ON feature_lifecycles.feature = v.feature AND feature_lifecycles.stage = v.stage
                    WHERE feature_lifecycles.feature IS NULL AND feature_lifecycles.stage IS NULL
                `))
            .insert((query) => {
            query.select('feature', 'stage').from('new_stages');
        })
            .into('feature_lifecycles')
            .onConflict(['feature', 'stage'])
            .ignore();
        await query;
    }
    async get(feature) {
        const results = await this.db('feature_lifecycles')
            .where({ feature })
            .orderBy('created_at', 'asc');
        return results.map(({ stage, created_at }) => ({
            stage,
            enteredStageAt: created_at,
        }));
    }
    async delete(feature) {
        await this.db('feature_lifecycles').where({ feature }).del();
    }
    async deleteStage(stage) {
        await this.db('feature_lifecycles')
            .where({
            stage: stage.stage,
            feature: stage.feature,
        })
            .del();
    }
    async stageExists(stage) {
        const result = await this.db.raw(`SELECT EXISTS(SELECT 1 FROM feature_lifecycles WHERE stage = ? and feature = ?) AS present`, [stage.stage, stage.feature]);
        const { present } = result.rows[0];
        return present;
    }
}
exports.FeatureLifecycleStore = FeatureLifecycleStore;
//# sourceMappingURL=feature-lifecycle-store.js.map