import { Injectable } from '@nestjs/common';
import { PrismaService } from '../../prisma/prisma.service';

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

  async findAll(params: { page?: number; pageSize?: number; status?: string }) {
    const page = Number(params.page ?? 1);
    const pageSize = Number(params.pageSize ?? 20);
    const where: any = { deletedAt: null };
    if (params.status) where.status = params.status;

    const [items, total] = await Promise.all([
      this.prisma.user.findMany({
        where,
        skip: (page - 1) * pageSize,
        take: pageSize,
        orderBy: { createdAt: 'desc' },
        select: {
          id: true, nickname: true, avatar: true, phone: true, email: true,
          status: true, memberPlan: true, createdAt: true, lastLoginAt: true,
        },
      }),
      this.prisma.user.count({ where }),
    ]);

    return { items, total, page, pageSize };
  }

  async findById(id: number) {
    return this.prisma.user.findUnique({
      where: { id },
      select: {
        id: true, nickname: true, avatar: true, phone: true, email: true,
        status: true, memberPlan: true, memberExpire: true, sandboxDaily: true,
        createdAt: true, lastLoginAt: true,
      },
    });
  }

  async updateProfile(id: number, data: { nickname?: string; avatar?: string }) {
    return this.prisma.user.update({ where: { id }, data });
  }
}
