import db, { schema, dbNamespace } from '../../db/database.js';
import { ScheduleStatus, SyncCommandToScheduleStatus } from '../../models/Sync.js';
import { getInterval } from '../nango-config.service.js';
import SyncClient from '../../clients/sync.client.js';
import { createActivityLogDatabaseErrorMessageAndEnd } from '../activity/activity.service.js';
import { Ok, Err } from '@nangohq/utils';
const TABLE = dbNamespace + 'sync_schedules';
export const createSchedule = async (sync_id, frequency, offset, status, schedule_id) => {
    await db.knex.from(TABLE).insert({
        sync_id,
        status,
        schedule_id,
        frequency,
        offset
    });
};
export const getScheduleById = async (schedule_id) => {
    const result = await schema().select('*').from(TABLE).where({ schedule_id, deleted: false }).first();
    return result || null;
};
export const getSchedule = async (sync_id) => {
    const result = await schema().select('*').from(TABLE).where({ sync_id, deleted: false }).first();
    if (result) {
        return result;
    }
    return null;
};
export const getSyncSchedules = async (sync_id) => {
    const result = await schema().select('*').from(TABLE).where({ sync_id, deleted: false });
    if (Array.isArray(result) && result.length > 0) {
        return result;
    }
    return [];
};
export const deleteScheduleForSync = async (sync_id, environmentId) => {
    const syncClient = await SyncClient.getInstance();
    const schedule = await getSchedule(sync_id);
    if (schedule && syncClient) {
        await syncClient.deleteSyncSchedule(schedule?.schedule_id, environmentId);
    }
};
export const markAllAsStopped = async () => {
    await schema().update({ status: ScheduleStatus.STOPPED }).from(TABLE);
};
export const updateScheduleStatus = async (schedule_id, status, activityLogId, environment_id, logCtx) => {
    try {
        await schema().update({ status: SyncCommandToScheduleStatus[status] }).from(TABLE).where({ schedule_id, deleted: false });
        return Ok(true);
    }
    catch (error) {
        if (activityLogId) {
            await createActivityLogDatabaseErrorMessageAndEnd(`Failed to update schedule status to ${status} for schedule_id: ${schedule_id}.`, error, activityLogId, environment_id);
            await logCtx?.error(`Failed to update schedule status to ${status} for schedule_id: ${schedule_id}`, { error });
        }
        return Err(error);
    }
};
export const updateSyncScheduleFrequency = async (sync_id, interval, syncName, environmentId, activityLogId, logCtx) => {
    const existingSchedule = await getSchedule(sync_id);
    if (!existingSchedule) {
        return { success: true, error: null, response: false };
    }
    const { success, error, response } = getInterval(interval, new Date());
    if (!success || response === null) {
        return { success: false, error, response: null };
    }
    const { interval: frequency, offset } = response;
    if (existingSchedule.frequency !== frequency) {
        await schema().update({ frequency }).from(TABLE).where({ sync_id, deleted: false });
        const syncClient = await SyncClient.getInstance();
        await syncClient?.updateSyncSchedule(existingSchedule.schedule_id, frequency, offset, environmentId, syncName, activityLogId, logCtx);
        return { success: true, error: null, response: true };
    }
    return { success: true, error: null, response: false };
};
export const updateOffset = async (schedule_id, offset) => {
    await schema().update({ offset }).from(TABLE).where({ schedule_id, deleted: false });
};
export async function softDeleteSchedules({ syncId, limit }) {
    return db
        .knex('_nango_sync_schedules')
        .update({
        deleted: true,
        deleted_at: db.knex.fn.now()
    })
        .whereIn('id', function (sub) {
        sub.select('id').from('_nango_sync_schedules').where({ deleted: false, sync_id: syncId }).limit(limit);
    });
}
export async function getRunningSchedules({ limit, offset }) {
    const query = db
        .knex('_nango_sync_schedules')
        .select('id', 'schedule_id', 'sync_id')
        .where({ status: ScheduleStatus.RUNNING, deleted: false })
        .orderBy('id')
        .limit(limit);
    if (offset) {
        query.where('id', '>', offset);
    }
    return query;
}
//# sourceMappingURL=schedule.service.js.map