import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { SysRole } from '../../entities/SysRole';
// 使用原生 Date 对象替代时间工具函数

@Injectable()
export class CoreRoleService {
  constructor(
    @InjectRepository(SysRole)
    private sysRoleRepository: Repository<SysRole>,
  ) {}

  async createRole(roleData: Partial<SysRole>): Promise<SysRole> {
    const role = this.sysRoleRepository.create({
      ...roleData,
      // TypeORM 会自动处理时间戳
    });

    return await this.sysRoleRepository.save(role);
  }

  async getRoleById(role_id: number): Promise<SysRole | null> {
    return await this.sysRoleRepository.findOne({
      where: { role_id },
    });
  }

  async getRoleByName(role_name: string, site_id: number): Promise<SysRole | null> {
    return await this.sysRoleRepository.findOne({
      where: { role_name, site_id },
    });
  }

  async updateRole(role_id: number, updateData: Partial<SysRole>): Promise<SysRole> {
    const role = await this.getRoleById(role_id);
    if (!role) {
      throw new NotFoundException('角色不存在');
    }

    Object.assign(role, {
      ...updateData,
      // TypeORM 会自动处理时间戳
    });

    return await this.sysRoleRepository.save(role);
  }

  async deleteRole(role_id: number): Promise<void> {
    const role = await this.getRoleById(role_id);
    if (!role) {
      throw new NotFoundException('角色不存在');
    }

    await this.sysRoleRepository.remove(role);
  }

  async getRolesByAppType(site_id: number): Promise<SysRole[]> {
    return await this.sysRoleRepository.find({
      where: { site_id },
      order: { create_time: 'DESC' },
    });
  }

  async getActiveRolesByAppType(site_id: number): Promise<SysRole[]> {
    return await this.sysRoleRepository.find({
      where: { site_id, status: 1 },
      order: { create_time: 'DESC' },
    });
  }

  async isRoleNameExists(role_name: string, site_id: number, exclude_role_id?: number): Promise<boolean> {
    const where: any = { role_name, site_id };
    
    if (exclude_role_id) {
      where.role_id = { $ne: exclude_role_id };
    }

    const count = await this.sysRoleRepository.count({ where });
    return count > 0;
  }

  async getRoleStats(site_id: number): Promise<any> {
    const total = await this.sysRoleRepository.count({ where: { site_id } });
    const active = await this.sysRoleRepository.count({ where: { site_id, status: 1 } });
    const inactive = await this.sysRoleRepository.count({ where: { site_id, status: 0 } });

    return {
      total,
      active,
      inactive,
    };
  }
} 