import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { CreateRoleDto } from './dto/create-role.dto';
import { UpdateRoleDto } from './dto/update-role.dto';

@Injectable()
export class RolesService {
  constructor(private prisma: PrismaService) {}

  async create(createRoleDto: CreateRoleDto, tenantId: number) {
    const { permissionIds, ...roleData } = createRoleDto;
    
    // 验证权限是否属于该租户
    if (permissionIds && permissionIds.length > 0) {
      const permissions = await this.prisma.permission.findMany({
        where: {
          id: { in: permissionIds },
          tenantId,
        },
      });
      if (permissions.length !== permissionIds.length) {
        throw new NotFoundException('部分权限不存在或不属于该租户');
      }
    }
    
    return this.prisma.role.create({
      data: {
        ...roleData,
        tenantId,
        permissions:
          permissionIds && permissionIds.length > 0
            ? {
                create: permissionIds.map((permissionId) => ({
                  permissionId,
                })),
              }
            : undefined,
      },
      include: {
        permissions: {
          include: {
            permission: true,
          },
        },
      },
    });
  }

  async findAll(page: number = 1, pageSize: number = 10, tenantId?: number) {
    const skip = (page - 1) * pageSize;
    const where = tenantId ? { tenantId } : {};
    
    const [list, total] = await Promise.all([
      this.prisma.role.findMany({
        where,
        skip,
        take: pageSize,
        include: {
          permissions: {
            include: {
              permission: true,
            },
          },
        },
      }),
      this.prisma.role.count({ where }),
    ]);

    return {
      list,
      total,
      page,
      pageSize,
    };
  }

  async findOne(id: number, tenantId?: number) {
    const where: any = { id };
    if (tenantId) {
      where.tenantId = tenantId;
    }

    const role = await this.prisma.role.findFirst({
      where,
      include: {
        permissions: {
          include: {
            permission: true,
          },
        },
      },
    });

    if (!role) {
      throw new NotFoundException('角色不存在');
    }

    return role;
  }

  async update(id: number, updateRoleDto: UpdateRoleDto, tenantId?: number) {
    const { permissionIds, ...roleData } = updateRoleDto;
    
    // 验证角色是否存在且属于该租户
    await this.findOne(id, tenantId);
    
    const data: any = { ...roleData };

    // 如果提供了 permissionIds，更新权限关联
    if (permissionIds !== undefined && tenantId) {
      // 验证权限是否属于该租户
      const permissions = await this.prisma.permission.findMany({
        where: {
          id: { in: permissionIds },
          tenantId,
        },
      });
      if (permissions.length !== permissionIds.length) {
        throw new NotFoundException('部分权限不存在或不属于该租户');
      }

      // 先删除所有现有权限关联
      await this.prisma.rolePermission.deleteMany({
        where: { roleId: id },
      });

      // 创建新的权限关联
      if (permissionIds.length > 0) {
        data.permissions = {
          create: permissionIds.map((permissionId) => ({
            permissionId,
          })),
        };
      }
    }

    return this.prisma.role.update({
      where: { id },
      data,
      include: {
        permissions: {
          include: {
            permission: true,
          },
        },
      },
    });
  }

  async remove(id: number, tenantId?: number) {
    // 验证角色是否存在且属于该租户
    await this.findOne(id, tenantId);
    
    return this.prisma.role.delete({
      where: { id },
    });
  }
}
