import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../../infrastructure/database/prisma.service';

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

  async findProfileByUserId(userId: string) {
    const user = await this.prisma.user.findUnique({
      where: { id: userId },
      select: {
        id: true,
        email: true,
        nickname: true,
        avatarUrl: true,
        role: true,
        status: true,
        onboardingCompleted: true,
        createdAt: true,
        profile: true,
        preferences: true,
      },
    });

    if (!user) {
      throw new NotFoundException('用户不存在');
    }

    const { profile, preferences, ...rest } = user;
    return {
      ...rest,
      profile: profile ?? null,
      preferences: preferences ?? null,
    };
  }

  async updateProfile(userId: string, dto: any) {
    return this.prisma.user.update({
      where: { id: userId },
      data: {
        nickname: dto.nickname,
        avatarUrl: dto.avatarUrl,
      },
    });
  }

  async findUserProfile(userId: string) {
    const profile = await this.prisma.userProfile.findUnique({
      where: { userId },
    });
    return profile ?? null;
  }

  async upsertUserProfile(userId: string, dto: {
    learningIdentity?: string;
    learningDirection?: string;
    bio?: string;
    currentGoal?: string;
  }) {
    return this.prisma.userProfile.upsert({
      where: { userId },
      create: { userId, ...dto },
      update: dto,
    });
  }

  async updatePreferences(userId: string, dto: any) {
    return this.prisma.userPreference.upsert({
      where: { userId },
      create: {
        userId,
        defaultFocusMinutes: dto.defaultFocusMinutes ?? 25,
        aiSuggestionLevel: dto.aiSuggestionLevel ?? 'normal',
        language: dto.language ?? 'zh-CN',
        appearance: dto.appearance ?? 'system',
        notificationEnabled: dto.notificationEnabled ?? true,
      },
      update: dto,
    });
  }
}
