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: {
          name: dto.companyName,
        },
      });

      return tx.user.create({
        data: {
          name: dto.name,
          email: dto.email,
          password: hashedPassword,
          companyId: company.id,
        },
        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: number) {
    return this.prisma.user.findUnique({ where: { id }, include: { company: true } });
  }

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

    const { password, refreshToken, ...rest } = user;
    return rest;
  }
}
