import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { CreatePermissionDto } from './dto/create-permission.dto';
import { UpdatePermissionDto } from './dto/update-permission.dto';

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

  async create(createPermissionDto: CreatePermissionDto, tenantId: number) {
    try {
      return await this.prisma.permission.create({
        data: {
          ...createPermissionDto,
          tenantId,
          modifyTime: new Date(),
        },
      });
    } catch (error: any) {
      console.error('创建权限失败:', error);
      if (error.code === 'P2002') {
        throw new BadRequestException('权限编码或资源操作组合已存在');
      }
      throw error;
    }
  }

  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.permission.findMany({
        where,
        skip,
        take: pageSize,
        orderBy: {
          createTime: 'desc',
        },
      }),
      this.prisma.permission.count({ where }),
    ]);

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

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

    const permission = await this.prisma.permission.findFirst({
      where,
    });

    if (!permission) {
      throw new NotFoundException('权限不存在');
    }

    return permission;
  }

  async update(id: number, updatePermissionDto: UpdatePermissionDto, tenantId?: number) {
    // 检查权限是否存在
    await this.findOne(id, tenantId);

    return this.prisma.permission.update({
      where: { id },
      data: updatePermissionDto,
    });
  }

  async remove(id: number, tenantId?: number) {
    // 检查权限是否存在
    await this.findOne(id, tenantId);

    return this.prisma.permission.delete({
      where: { id },
    });
  }
}
