import { Inject, Injectable, forwardRef } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { LogClient } from '../log/entities/log.entity';
import { LogAction, LogType } from '../log/log.interface';
import { LogService } from '../log/log.service';
import { OrderEntity } from '../order/entities/order.entity';
import { UserEntity } from '../user/entities/user.entity';
import { UserService } from '../user/user.service';
import { PointEntity } from './entities/point.entity';

@Injectable()
export class PointService {
  constructor(
    @InjectRepository(PointEntity)
    private pointRepository: Repository<PointEntity>,
    private logService: LogService,

    @Inject(forwardRef(() => UserService))
    private readonly userService: UserService,
  ) {}

  /**
   * -------------------------------------------------------
   * Add point
   */
  async add(user: UserEntity, point: number, description: string) {
    const newPoint = new PointEntity();

    newPoint.userId = user.id;
    newPoint.point = point;
    newPoint.description = description;
    newPoint.createdAt = new Date();
    newPoint.updatedAt = new Date();

    const { identifiers } = await this.pointRepository
      .createQueryBuilder()
      .insert()
      .values(newPoint)
      .execute();

    const pointId = identifiers[0].id;
    const data = await this.pointRepository.findOne(pointId);

    return data;
  }

  /**
   * -------------------------------------------------------
   * Add point to moaref
   */
  async addToMoaref(order: OrderEntity, point: number, description: string) {
    if (!order.user.moaref) return false;

    const user = await this.userService.findByUserKey(order.user.moaref);
    if (!user) return false;

    const data = await this.add(user, point, description);

    // LOG ADD POINT
    await this.logService.add({
      type: LogType.user,
      action: LogAction.insert,
      client: LogClient.system,
      message: `${point} امتیاز به ${user.name} ${user.surName} جهت معرفی ${order.user.name} ${order.user.surName} بابت فاکتور شماره ${order.orderNumber} تخصیص داده شد.`,
      affectedId: user.id,
      item: {
        point,
        orderId: order.id,
        orderNumber: order.orderNumber,
      },
    });

    return data;
  }
}
