import { Injectable } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { CreateUserDto } from './dto/create-user.dto';

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

  async createWithCompany(dto: CreateUserDto, hashedPassword: string) {
    return this.prisma.$transaction(async (tx: Prisma.TransactionClient) => {
      const company = await tx.company.create({
        data: {
          corporateName: dto.companyName,
          cnpj: dto.cnpj || '',
          licenseNumber: dto.licenseNumber || '',
        },
      });

      return tx.user.create({
        data: {
          name: dto.name,
          email: dto.email,
          passwordHash: hashedPassword,
          companyId: company.id,
          role: dto.role || 'ADMIN',
        },
        include: { company: true },
      });
    });
  }

  async findByEmail(email: string) {
    return this.prisma.user.findUnique({ where: { email } });
  }

  async findByEmailWithCompany(email: string) {
    return this.prisma.user.findUnique({ where: { email }, include: { company: true } });
  }

  async findById(id: string) {
    return this.prisma.user.findUnique({ where: { id }, include: { company: true } });
  }

  async getSafeUser(id: string) {
    const user = await this.findById(id);
    if (!user) return null;

    const { passwordHash, ...rest } = user;
    return rest;
  }
}
