// user-permissions.service.ts
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UserPermission } from './entities/user-permission.entity';
import { UserPermissionCondition } from './../user-permission-conditions/entities/user-permission-condition.entity';
import {
  CreateUserPermissionDto,
  UpdateUserPermissionDto,
} from './dto/create-user-permission.dto';

@Injectable()
export class UserPermissionsService {
  constructor(
    @InjectRepository(UserPermission, 'scheme_dbs')
    private readonly repo: Repository<UserPermission>,

    @InjectRepository(UserPermissionCondition, 'scheme_dbs')
    private readonly conditionRepo: Repository<UserPermissionCondition>,
  ) {}

  // ✅ Create permission for user
  async create(dto: CreateUserPermissionDto): Promise<UserPermission> {
    const permission = this.repo.create({
      user: { id: dto.userId },
      permission: { id: dto.permissionId },
    });

    if (dto.conditions?.length) {
      permission.conditions = dto.conditions.map((c) =>
        this.conditionRepo.create({ ...c }),
      );
    }

    return this.repo.save(permission);
  }

  // ✅ Find all permissions for user
  // Fix: findAllForUser — add permission.module relation
  async findAllForUser(userId: number): Promise<UserPermission[]> {
    return this.repo.find({
      where: { user: { id: userId } },
      relations: [
        'permission',
        'permission.module',
        'conditions',
        'conditions.module',
      ],
    });
  }

  // ✅ Update user permission
  async update(
    id: number,
    dto: UpdateUserPermissionDto,
  ): Promise<UserPermission> {
    const permission = await this.repo.findOne({
      where: { id },
      relations: ['conditions'],
    });
    if (!permission) throw new NotFoundException('UserPermission not found');

    if (dto.permissionId)
      permission.permission = { id: dto.permissionId } as any;

    if (dto.conditions) {
      permission.conditions = dto.conditions.map((c) =>
        this.conditionRepo.create({ ...c }),
      );
    }

    return this.repo.save(permission);
  }

  // ✅ Delete user permission
  async remove(id: number): Promise<void> {
    const permission = await this.repo.findOne({ where: { id } });
    if (!permission) throw new NotFoundException('UserPermission not found');
    await this.repo.remove(permission);
  }
}
