import { Injectable } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
import { InjectRepository } from '@nestjs/typeorm';
import { IsNull, Not, Repository } from 'typeorm';
import { AppUser } from 'src/app_users/entities/app_user.entity';
import { AppUsersStep } from 'src/app_users_steps/entities/app_users_step.entity';
import * as moment from 'moment';
import * as admin from 'firebase-admin';
import { SendNotificationService } from 'src/common/push-notification';

@Injectable()
export class CronService {
  constructor(
    @InjectRepository(AppUser)
    private readonly userRepo: Repository<AppUser>,

    private readonly sendNotificationService: SendNotificationService,
  ) {}

  @Cron('0 7 * * *', {
    timeZone: 'Europe/Amsterdam',
  })
  async handleDailyZeroStepNotification() {
    const users = await this.userRepo.find({
      where: {
        notify: true,
        fcm_token: Not(IsNull()),
      },
      relations: ['user_steps'],
    });

    const zeroStepUsers = users.filter((user) => {
      const totalSteps = user.user_steps.reduce(
        (total, step) => total + parseInt(step.steps || '0'),
        0,
      );
      return totalSteps === 0;
    });

    for (const user of zeroStepUsers) {
      await this.sendNotificationService.send(
        [user.fcm_token],
        'Je stappen worden niet gesynchroniseerd',
        'Bedankt dat je je gezondheid prioriteit geeft met ProVoet! Om je stappen correct bij te houden, geef alsjeblieft de benodigde toestemming zodat ProVoet je gezondheidsgegevens kan synchroniseren. https://provoet.pehoy.com/guide/',
        {
          user_id: user.id,
        },
      );
    }
  }
}
