import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { CreateExpenseDto } from './dto/create-expense.dto';
import { UpdateExpenseDto } from './dto/update-expense.dto';
import { UsersService } from '../users/users.service';
import { user_role } from '@prisma/client';

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

  create(createExpenseDto: CreateExpenseDto) {
    return this.prisma.expense.create({
      data: createExpenseDto,
    });
  }

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

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

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

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

  update(id: string, updateExpenseDto: UpdateExpenseDto) {
    return this.prisma.expense.update({
      where: { id },
      data: updateExpenseDto as any,
    });
  }

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