import {
  BadRequestException,
  Injectable,
  NotFoundException,
} from '@nestjs/common';
import { CreateStreakDto } from './dto/create-streak.dto';
import { UpdateStreakDto } from './dto/update-streak.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Streak } from './entities/streak.entity';
import { Repository } from 'typeorm';
import { StreakRepository } from './streaks.repository';
import { lan } from 'src/lan';
import isValidUuidV4 from 'src/common/uuid validator/uuid-validate';
import { isEmpty } from 'src/common/helper';
import { AppUser } from 'src/app_users/entities/app_user.entity';
import { AppUserRepository } from 'src/app_users/app_users.repository';

@Injectable()
export class StreaksService {
  constructor(
    @InjectRepository(Streak)
    private readonly streakEntity: Repository<Streak>,
    private readonly streakRepository: StreakRepository,
    private readonly appUserRepository: AppUserRepository,
  ) {}

  async create(createStreakDto: CreateStreakDto) {
    if (await this.streakRepository.isUnique(createStreakDto.streak_count)) {
      throw new BadRequestException(lan('data_already_exists'));
    }

    const streak = new Streak();
    Object.assign(streak, createStreakDto);

    const data = await this.streakEntity.save(streak);

    return data;
  }

  async findAll(
    take: number,
    skip: number,
    key?: string,
    order?: string,
    headers?: any,
  ) {
    return this.streakRepository.getAllStreaks(take, skip, key, order, headers);
  }

  async findAllStreak(
    take: number,
    skip: number,
    key: string,
    order: string,
    search: string,
    recent: boolean,
    province: string,
  ) {
    return await this.streakRepository.findAllStreak(
      take,
      skip,
      key,
      order,
      search,
      recent,
      province,
    );
  }

  async findOne(id: string) {
    if (!isValidUuidV4(id)) {
      throw new BadRequestException(lan('common.invalid_uuid_format'));
    }

    const data = await this.streakRepository.findById(id);

    if (isEmpty(data)) {
      throw new NotFoundException(lan('common.data_not_found'));
    }
    return data;
  }

  async findUserStreak(take: number, skip: number, userId: string) {
    if (userId) {
      const data = await this.appUserRepository.findUserId(userId);
      if (isEmpty(data)) {
        throw new BadRequestException(lan('common.data_not_found'));
      }
    }
    return await this.streakRepository.findAllUserStreak(take, skip, userId);
  }

  async findAllUserStreak() {
    await this.streakRepository.getAllStreaks();
  }

  async remove(id: string) {
    if (!isValidUuidV4(id)) {
      throw new BadRequestException(lan('common.invalid_uuid_format'));
    }

    const achievement = await this.streakRepository.findById(id);

    if (isEmpty(achievement)) {
      throw new NotFoundException(lan('common.data_not_found'));
    }

    await this.streakEntity.softDelete(id);
  }
}
