import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { CreateIncentiveDto } from './dto/create-incentive.dto';
import { UpdateIncentiveDto } from './dto/update-incentive.dto';
import { UsersService } from '../users/users.service';
import { user_role } from '@prisma/client';

@Injectable()
export class IncentivesService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly usersService: UsersService
  ) { }

  create(createIncentiveDto: CreateIncentiveDto) {
    return this.prisma.incentive.create({
      data: {
        ...createIncentiveDto,
        achievedAmount: 0,
      } as any,
    });
  }

  async findAll(user: any) {
    if (user.role === user_role.ADMIN) {
      return this.prisma.incentive.findMany({
        include: {
          user: true,
        },
      });
    }

    const subordinateIds = await this.usersService.getSubordinateIds(user.id);
    const allowedUserIds = [user.id, ...subordinateIds];

    return this.prisma.incentive.findMany({
      where: {
        userId: { in: allowedUserIds }
      },
      include: {
        user: true,
      },
    });
  }

  findOne(id: string) {
    return this.prisma.incentive.findUnique({
      where: { id },
      include: {
        user: true,
      },
    });
  }

  update(id: string, updateIncentiveDto: UpdateIncentiveDto) {
    return this.prisma.incentive.update({
      where: { id },
      data: updateIncentiveDto as any,
    });
  }

  remove(id: string) {
    return this.prisma.incentive.delete({
      where: { id },
    });
  }
}
