import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from '@/entities/user.entity';
import { QueryUserDto } from './dto/user.dto';

@Injectable()
export class AdminUserService {
  constructor(
    @InjectRepository(User)
    private userRepo: Repository<User>,
  ) {}

  async findAll(query: QueryUserDto) {
    const { page = 1, pageSize = 10, status, keyword } = query;
    const qb = this.userRepo.createQueryBuilder('user');

    if (status) {
      qb.andWhere('user.status = :status', { status });
    }

    if (keyword) {
      qb.andWhere(
        '(user.nickname LIKE :keyword OR user.phone LIKE :keyword)',
        { keyword: `%${keyword}%` },
      );
    }

    qb.orderBy('user.createdAt', 'DESC')
      .skip((page - 1) * pageSize)
      .take(pageSize);

    const [list, total] = await qb.getManyAndCount();

    return {
      list,
      total,
      page,
      pageSize,
      totalPages: Math.ceil(total / pageSize),
    };
  }

  async freeze(id: number) {
    await this.userRepo.update(id, { status: 'frozen' });
    return { message: '已冻结' };
  }

  async unfreeze(id: number) {
    await this.userRepo.update(id, { status: 'active' });
    return { message: '已解冻' };
  }
}
