import { ConflictException, Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { UsersService } from '../users/users.service';
import { UpdateProfileDto } from './dto';

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

  async get(userId: string) {
    return { message: 'Profile fetched successfully', data: this.users.toSafeUser(await this.users.ensureUser(userId)) };
  }

  async update(userId: string, dto: UpdateProfileDto) {
    if (dto.email) {
      const existing = await this.prisma.user.findFirst({
        where: { email: dto.email.toLowerCase(), id: { not: userId }, deletedAt: null },
      });
      if (existing) throw new ConflictException('Email already exists');
    }
    const user = await this.prisma.user.update({
      where: { id: userId },
      data: { ...dto, email: dto.email?.toLowerCase() },
    });
    return { message: 'Profile updated successfully', data: this.users.toSafeUser(user) };
  }

  async delete(userId: string) {
    await this.prisma.user.update({ where: { id: userId }, data: { deletedAt: new Date(), status: 'INACTIVE' } });
    await this.prisma.refreshToken.updateMany({ where: { userId, revokedAt: null }, data: { revokedAt: new Date() } });
    return { message: 'Profile deleted successfully', data: null };
  }
}
