import { Injectable, NotFoundException, ForbiddenException } from '@nestjs/common';
import * as bcrypt from 'bcryptjs';
import { PrismaService } from '../../prisma/prisma.service';

@Injectable()
export class UsersService {
  constructor(private prisma: PrismaService) {}

  async findAll(tenantId: string) {
    return this.prisma.user.findMany({
      where: { tenantId, isActive: true },
      select: { id: true, name: true, email: true, role: true, createdAt: true, avatarUrl: true },
    });
  }

  async create(tenantId: string, data: { name: string; email: string; password: string; role: string }) {
    const tenant = await this.prisma.tenant.findUnique({ where: { id: tenantId } });
    const count = await this.prisma.user.count({ where: { tenantId, isActive: true } });
    if (count >= (tenant?.maxUsers ?? 2)) {
      throw new ForbiddenException('Limite de usuários atingido. Faça upgrade do plano.');
    }
    const passwordHash = await bcrypt.hash(data.password, 12);
    return this.prisma.user.create({
      data: { tenantId, name: data.name, email: data.email, passwordHash, role: data.role as any },
      select: { id: true, name: true, email: true, role: true, createdAt: true },
    });
  }

  async remove(tenantId: string, id: string) {
    const user = await this.prisma.user.findFirst({ where: { id, tenantId } });
    if (!user) throw new NotFoundException('Usuário não encontrado');
    return this.prisma.user.update({ where: { id }, data: { isActive: false } });
  }
}
