import { Injectable, UnauthorizedException } from '@nestjs/common';
import { CreateAdminDto } from './dto/create-admin.dto';
import { Admin } from './entities/admin.entity';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { Town } from 'src/town/entities/town.entity';
import { ADMIN_ROLE } from 'src/shared/enum/admin-role.enum';
import { GetAdminDto } from './dto/get-admin.dto';

@Injectable()
export class AdminService {
  constructor(
    @InjectRepository(Admin) private adminRepository: Repository<Admin>,
    @InjectRepository(Town) private townRepository: Repository<Town>,
  ) {}
  async create(createAdminDto: CreateAdminDto) {
    let town: Town = null;
    if (createAdminDto.role == ADMIN_ROLE.ADMIN) {
      town = await this.townRepository.findOneByOrFail({ townId: createAdminDto.idTown });
    }
    await this.adminRepository.insert({ ...createAdminDto, idTown: town });
  }

  async findOne(email: string): Promise<Admin> {
    try {
      return await this.adminRepository.findOneByOrFail({ email });
    } catch (error) {
      throw new UnauthorizedException('Admin not found');
    }
  }

  async adminExists(email: string): Promise<boolean> {
    const admin = await this.adminRepository.findOneBy({ email });
    if (admin) return true;
    else return false;
  }

  async updatePassword(email: string, password: string) {
    await this.adminRepository.update({ email }, { password });
  }

  async findAllByTown(idTown: number): Promise<GetAdminDto[]> {
    const res: any[] = await this.adminRepository
      .createQueryBuilder('admin')
      .leftJoinAndSelect('admin.idTown', 'town')
      .where('admin.idTown = :idTown', { idTown: idTown })
      .getMany();
    const admins: GetAdminDto[] = res.map((admin): GetAdminDto => {
      return {
        email: admin.email,
        idTown: admin.idTown.townId,
        name: admin.name,
        lastName: admin.lastName,
        status: admin.status,
      };
    });
    return admins;
  }
}
