import { DataSource } from 'typeorm';
import { RoleMt } from '../entities/role.entity.mt';
import { ConcreteCrudService } from '@d8d/shared-crud';

export class RoleServiceMt extends ConcreteCrudService<RoleMt> {
  constructor(dataSource: DataSource) {
    super(RoleMt, {
      userTracking: {
        // 禁用用户追踪
      },
      tenantOptions: {
        tenantIdField: 'tenantId',
        autoExtractFromContext: true
      }
    });
  }

  /**
   * 根据角色名获取角色（自动添加租户过滤）
   */
  async getRoleByName(name: string, tenantId?: number): Promise<RoleMt | null> {
    try {
      const where: any = { name };

      // 如果提供了租户ID，添加租户过滤
      if (tenantId !== undefined) {
        where.tenantId = tenantId;
      }

      const roles = await this.repository.find({ where });
      return roles.length > 0 ? roles[0] : null;
    } catch (error) {
      console.error('Error getting role by name:', error);
      throw new Error('Failed to get role by name');
    }
  }

  /**
   * 检查角色是否拥有指定权限
   */
  async hasPermission(roleId: number, permission: string, tenantId?: number): Promise<boolean> {
    try {
      const role = await this.getById(roleId, [], tenantId);
      if (!role) return false;

      return role.permissions.includes(permission);
    } catch (error) {
      console.error('Error checking permission:', error);
      throw new Error('Failed to check permission');
    }
  }

  /**
   * 获取所有角色（自动添加租户过滤）
   */
  async getRoles(tenantId?: number): Promise<RoleMt[]> {
    try {
      const where: any = {};

      // 如果提供了租户ID，添加租户过滤
      if (tenantId !== undefined) {
        where.tenantId = tenantId;
      }

      return await this.repository.find({ where });
    } catch (error) {
      console.error('Error getting roles:', error);
      throw new Error(`Failed to get roles: ${error instanceof Error ? error.message : String(error)}`);
    }
  }

  /**
   * 根据ID获取角色（重写以添加租户过滤）
   */
  async getById(id: number, relations: string[] = [], userId?: string | number): Promise<RoleMt | null> {
    try {
      const where: any = { id };

      // 如果提供了租户ID（作为userId参数传递），添加租户过滤
      if (userId !== undefined && typeof userId === 'number') {
        where.tenantId = userId;
      }

      return await this.repository.findOne({ where, relations });
    } catch (error) {
      console.error('Error getting role by id:', error);
      throw new Error('Failed to get role by id');
    }
  }

  /**
   * 更新角色（重写以添加租户过滤）
   */
  async update(id: number, data: Partial<RoleMt>, userId?: string | number): Promise<RoleMt | null> {
    try {
      // 首先验证角色是否存在且属于指定租户
      const existingRole = await this.getById(id, [], userId);
      if (!existingRole) return null;

      // 更新角色
      await this.repository.update(id, data);

      // 返回更新后的角色
      return await this.getById(id, [], userId);
    } catch (error) {
      console.error('Error updating role:', error);
      throw new Error('Failed to update role');
    }
  }

  /**
   * 删除角色（重写以添加租户过滤）
   */
  async delete(id: number, userId?: string | number): Promise<boolean> {
    try {
      // 首先验证角色是否存在且属于指定租户
      const existingRole = await this.getById(id, [], userId);
      if (!existingRole) return false;

      // 删除角色
      const result = await this.repository.delete(id);
      return result.affected === 1;
    } catch (error) {
      console.error('Error deleting role:', error);
      throw new Error('Failed to delete role');
    }
  }
}