import { ConflictException, Injectable, NotFoundException } from '@nestjs/common';
import { Prisma, User } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';

export type SafeUser = Omit<User, 'passwordHash'>;

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

  async findActiveByEmail(email: string) {
    return this.prisma.user.findFirst({ where: { email: email.toLowerCase(), deletedAt: null } });
  }

  async findActiveById(id: string) {
    return this.prisma.user.findFirst({ where: { id, deletedAt: null } });
  }

  async create(data: Prisma.UserCreateInput) {
    const existing = await this.prisma.user.findUnique({ where: { email: data.email } });
    if (existing) throw new ConflictException('Email already exists');
    return this.prisma.user.create({ data: { ...data, email: data.email.toLowerCase() } });
  }

  toSafeUser(user: User): SafeUser {
    const { passwordHash: _passwordHash, ...safe } = user;
    return safe;
  }

  async ensureUser(id: string) {
    const user = await this.findActiveById(id);
    if (!user) throw new NotFoundException('User not found');
    return user;
  }
}
