import { Injectable, NotFoundException } from '@nestjs/common';
import { CreateGroupDto } from '../dto/create-group.dto';
import { UpdateGroupDto } from '../dto/update-group.dto';
import { GroupRepository } from '../repositories/group.repository';
import { EntityManager } from '@mikro-orm/postgresql';
import { RequiredEntityData } from '@mikro-orm/core';
import { Group } from '../entities/group.entity';
import { GroupMessage } from 'src/common/enums/message.enum';

@Injectable()
export class GroupService {
  constructor(
    private readonly groupRepository: GroupRepository,
    private readonly em: EntityManager,
  ) {}

  async create(dto: CreateGroupDto): Promise<Group> {
    const data: RequiredEntityData<Group> = {
      name: dto.name,
    };

    const group = this.groupRepository.create(data);
    await this.em.persistAndFlush(group);
    return group;
  }

  async findOne(id: string): Promise<Group> {
    const group = await this.groupRepository.findOne({ id }, { populate: ['icons'] });
    if (!group) {
      throw new NotFoundException(GroupMessage.NOT_FOUND);
    }
    return group;
  }

  async update(id: string, dto: UpdateGroupDto): Promise<Group> {
    const group = await this.groupRepository.findOne({ id });
    if (!group) {
      throw new NotFoundException(GroupMessage.NOT_FOUND);
    }
    this.em.assign(group, dto);
    await this.em.persistAndFlush(group);
    return group;
  }

  async remove(id: string): Promise<void> {
    const group = await this.groupRepository.findOne({ id }, { populate: ['icons'] });
    if (!group) {
      throw new NotFoundException(GroupMessage.NOT_FOUND);
    }
    await this.em.removeAndFlush(group);
  }

  findAllGroups(): Promise<Group[]> {
    return this.groupRepository.find({}, { populate: ['icons'] });
  }
}
