import { Injectable, NotFoundException, BadRequestException, ConflictException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Like } from 'typeorm';
import { Admin } from '@/entities/admin.entity';
import { CreateAdminDto, UpdateAdminDto, UpdateAdminPasswordDto, QueryAdminDto } from './dto/admin.dto';
import { AdminRole, AdminStatus } from '@/common/constants/admin.constant';
import * as bcrypt from 'bcrypt';

@Injectable()
export class AdminManageService {
  constructor(
    @InjectRepository(Admin)
    private adminRepo: Repository<Admin>,
  ) {}

  async getAdminList(query: QueryAdminDto) {
    const { username, name, role, status, page = 1, pageSize = 20 } = query;

    const queryBuilder = this.adminRepo.createQueryBuilder('admin');

    if (username) {
      queryBuilder.andWhere('admin.username LIKE :username', { username: `%${username}%` });
    }

    if (name) {
      queryBuilder.andWhere('admin.name LIKE :name', { name: `%${name}%` });
    }

    if (role) {
      queryBuilder.andWhere('admin.role = :role', { role });
    }

    if (status) {
      queryBuilder.andWhere('admin.status = :status', { status });
    }

    queryBuilder.orderBy('admin.createdAt', 'DESC');

    const skip = (page - 1) * pageSize;
    queryBuilder.skip(skip).take(pageSize);

    const [items, total] = await queryBuilder.getManyAndCount();

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

  async getAdminById(id: number) {
    const admin = await this.adminRepo.findOne({ where: { id } });
    if (!admin) {
      throw new NotFoundException('管理员不存在');
    }
    return admin;
  }

  async createAdmin(dto: CreateAdminDto) {
    const existingAdmin = await this.adminRepo.findOne({ where: { username: dto.username } });
    if (existingAdmin) {
      throw new ConflictException('用户名已存在');
    }

    const hashedPassword = await bcrypt.hash(dto.password, 10);

    const admin = this.adminRepo.create({
      ...dto,
      password: hashedPassword,
    });

    return this.adminRepo.save(admin);
  }

  async updateAdmin(id: number, dto: UpdateAdminDto) {
    const admin = await this.getAdminById(id);

    Object.assign(admin, dto);

    return this.adminRepo.save(admin);
  }

  async updateAdminPassword(id: number, dto: UpdateAdminPasswordDto) {
    const admin = await this.getAdminById(id);

    const hashedPassword = await bcrypt.hash(dto.password, 10);
    admin.password = hashedPassword;

    await this.adminRepo.save(admin);

    return { message: '密码修改成功' };
  }

  async deleteAdmin(id: number) {
    const admin = await this.getAdminById(id);

    if (admin.role === AdminRole.SUPER_ADMIN) {
      throw new BadRequestException('不能删除超级管理员');
    }

    await this.adminRepo.remove(admin);

    return { message: '删除成功' };
  }

  async toggleAdminStatus(id: number) {
    const admin = await this.getAdminById(id);

    if (admin.role === AdminRole.SUPER_ADMIN) {
      throw new BadRequestException('不能冻结超级管理员');
    }

    admin.status = admin.status === AdminStatus.ACTIVE ? AdminStatus.FROZEN : AdminStatus.ACTIVE;

    return this.adminRepo.save(admin);
  }
}
