import { ForbiddenException, Injectable, NotFoundException } from '@nestjs/common';
import { AuthUser } from '../../common/current-user.decorator';
import { PrismaService } from '../prisma/prisma.service';

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

  async findAll(user: AuthUser, query: any = {}) {
    const page = Math.max(Number(query.page ?? 1), 1);
    const pageSize = Math.min(Math.max(Number(query.pageSize ?? query.limit ?? 20), 1), 100);
    const where = { tenantId: user.tenantId ?? '__platform-roles-hidden__' };
    const include = {
      permissions: { include: { permission: true } },
      regionScopes: { include: { region: true } },
    };

    const [items, total] = await Promise.all([
      this.prisma.role.findMany({
        where,
        include,
        orderBy: { createdAt: 'desc' },
        skip: (page - 1) * pageSize,
        take: pageSize,
      }),
      this.prisma.role.count({ where }),
    ]);

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

  permissions(user: AuthUser) {
    return this.prisma.permission.findMany({
      where: user.tenantId ? { code: { not: 'tenants:manage' } } : { code: 'tenants:manage' },
      orderBy: [{ sort: 'asc' }, { createdAt: 'asc' }],
    });
  }

  async create(user: AuthUser, dto: any) {
    if (!user.tenantId) {
      throw new ForbiddenException('平台超级管理员不能在角色页面配置角色');
    }

    return this.prisma.role.create({
      data: {
        name: dto.name,
        code: dto.code,
        description: dto.description,
        tenantId: user.tenantId,
        permissions: { create: dto.permissionIds?.map((permissionId: string) => ({ permissionId })) ?? [] },
        regionScopes: { create: dto.regionIds?.map((regionId: string) => ({ regionId })) ?? [] },
      },
    });
  }

  async update(user: AuthUser, id: string, dto: any) {
    await this.ensureTenantRole(user, id);
    await this.prisma.rolePermission.deleteMany({ where: { roleId: id } });
    await this.prisma.roleRegionScope.deleteMany({ where: { roleId: id } });

    return this.prisma.role.update({
      where: { id },
      data: {
        name: dto.name,
        code: dto.code,
        description: dto.description,
        permissions: { create: dto.permissionIds?.map((permissionId: string) => ({ permissionId })) ?? [] },
        regionScopes: { create: dto.regionIds?.map((regionId: string) => ({ regionId })) ?? [] },
      },
    });
  }

  async remove(user: AuthUser, id: string) {
    await this.ensureTenantRole(user, id);
    return this.prisma.role.delete({ where: { id } });
  }

  private async ensureTenantRole(user: AuthUser, id: string) {
    if (!user.tenantId) {
      throw new ForbiddenException('平台超级管理员不能在角色页面配置角色');
    }
    const role = await this.prisma.role.findFirst({ where: { id, tenantId: user.tenantId } });
    if (!role) {
      throw new NotFoundException('角色不存在或无权限访问');
    }
    return role;
  }
}
