import { BadRequestException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Role } from '../users/entities/role.entity';
import { User } from '../users/entities/user.entity';
import { assertAdmin } from './admin-access';
import { normalizePermissions, permissionResources } from './permission-resources';

@Injectable()
export class AdminPermissionsService {
  constructor(
    @InjectRepository(Role)
    private readonly rolesRepository: Repository<Role>,
  ) {}

  async listPermissions(actor: User) {
    assertAdmin(actor);
    const roles = await this.rolesRepository.find({ order: { code: 'ASC' } });
    return {
      resources: permissionResources,
      roles: roles.map((role) => ({
        code: role.code,
        name: role.name,
        permissions: role.permissions || {},
      })),
    };
  }

  async updateRolePermissions(
    actor: User,
    roleCode: string,
    permissions: Record<string, string[]>,
  ) {
    assertAdmin(actor);
    const role = await this.rolesRepository.findOne({ where: { code: roleCode } });
    if (!role) {
      throw new BadRequestException('角色不存在');
    }
    if (role.code === 'super_admin') {
      throw new BadRequestException('超级管理员权限不可修改');
    }

    const normalized = normalizePermissions(permissions);

    role.permissions = normalized;
    await this.rolesRepository.save(role);
    return {
      code: role.code,
      name: role.name,
      permissions: role.permissions,
    };
  }
}
