import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '@chatapp/database';

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

  async findById(id: string) {
    const user = await this.prisma.user.findUnique({ where: { id } });
    if (!user || user.isDeleted) throw new NotFoundException('User not found');
    const { passwordHash, ...result } = user;
    return result;
  }

  async listByWorkspace(workspaceId: string) {
    const members = await this.prisma.workspaceMember.findMany({
      where: { workspaceId, deactivatedAt: null },
      include: { user: true },
    });
    return members.map(m => {
      const { passwordHash, ...user } = m.user as any;
      return { ...user, role: m.role, joined_at: m.joinedAt };
    });
  }

  async updateProfile(userId: string, dto: any) {
    const allowed = ['displayName', 'realName', 'title', 'bio', 'avatarUrl', 'phone', 'pronouns', 'timezone', 'locale'];
    const data: any = {};
    for (const key of allowed) {
      if (dto[key] !== undefined) data[key] = dto[key];
    }
    const updated = await this.prisma.user.update({ where: { id: userId }, data });
    const { passwordHash, ...result } = updated;
    return result;
  }

  async updateStatus(userId: string, dto: any) {
    const data: any = {};
    if (dto.text !== undefined) data.statusText = dto.text;
    if (dto.emoji !== undefined) data.statusEmoji = dto.emoji;
    if (dto.expires_at) data.statusExpires = new Date(dto.expires_at);
    const updated = await this.prisma.user.update({ where: { id: userId }, data });
    const { passwordHash, ...result } = updated;
    return {
      status_text: result.statusText,
      status_emoji: result.statusEmoji,
      status_expires: result.statusExpires,
    };
  }

  async updatePresence(userId: string, presence: string) {
    await this.prisma.user.update({
      where: { id: userId },
      data: { presence, lastActiveAt: new Date() },
    });
    return { presence };
  }
}