import { Injectable, Query } from '@nestjs/common';
import { Cron, Interval } from '@nestjs/schedule';
// import { ModelService } from 'src/model/model.service';
import { ModelService } from '../model/model.service';
import moment from 'moment';
import * as fs from 'fs';
import * as path from "path";
import { config } from 'dotenv';
import * as mongoose from 'mongoose';
import { Types } from 'mongoose'
import { CallService } from '../call/call.service';
config();

const SERVER_URL = process.env.ENV;

@Injectable()
export class CronService {
    constructor(

        private model: ModelService,
        private CallService: CallService
    ) {
    }
    // @Cron("*/1 * * * *")
    // @Interval(300000)
    @Cron('*/1 * * * *')
    handleCron() {
        console.log("cronjob  is running");

        this.status_update()
    }

    async status_update() {
        try {
            let start_date = moment().subtract(15, 'minutes').valueOf()

            let all_chat = await this.model.CallModel.find({
                created_at: { $lte: start_date },
                type: { $in: ["CHAT", "VOICE_CHAT"]},
                status: "ACTIVE"
            },
                {},
                { lean: true }
            )


            for (let i = 0; i < all_chat.length; i++) {
                let { _id: chat_id } = all_chat[i]
                await this.model.CallModel.findOneAndUpdate(
                    { _id: chat_id },
                    {
                        status: "COMPLETE",
                        updated_at: +new Date()
                    }
                )

                await this.CallService.chat_summerize(chat_id)
            }
        } catch (error) {
            throw error
        }
    }

}