import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common'
import { In, Repository, UpdateResult } from 'typeorm'
import { InjectRepository } from '@nestjs/typeorm'
import { ApiType, ApiUser } from './entities/api-user.entity'
import { ApiUserDto } from './dto/api-user.dto'
import { paginate, Pagination } from 'nestjs-typeorm-paginate'
import { PageRequest } from '../common/dto/page-request'
import { Role } from 'src/model/role.enum'
import { Users } from '../users/entities/users.entity'

@Injectable()
export class ApiUserService {
    constructor(
        @InjectRepository(ApiUser)
        private readonly apiUserRepository: Repository<ApiUser>,
        @InjectRepository(Users)
        private readonly userRepository: Repository<Users>
    ) {}

    async findAll(req: PageRequest<ApiUser>): Promise<Pagination<ApiUser>> {
        return await paginate<ApiUser>(this.apiUserRepository, req.page, req.search)
    }

    public async create(userId: number) {
        let user = await this.findUserById(userId)
        if (!user.roles.includes(Role.Api)) {
            throw new BadRequestException('Not api user')
        }
        let apiUser = new ApiUser()
        apiUser.name = user.name
        apiUser.type = ApiType.Customer
        apiUser.userId = userId
        const result = await this.apiUserRepository.save(apiUser)
        return result
    }

    public async findById(id: number): Promise<ApiUser> {
        const apiUser = await this.apiUserRepository.findOneBy({
            id: +id
        })
        return apiUser
    }

    public async findUserById(id: number): Promise<Users> {
        const user = await this.userRepository.findOneBy({
            id: +id
        })
        return user
    }

    public async findByUserId(id: number): Promise<ApiUser> {
        const user = await this.apiUserRepository.findOneBy({
            userId: +id
        })
        return user
    }

    public async findByCode(code: string): Promise<ApiUser> {
        const apiUser = await this.apiUserRepository.findOneBy({
            code: code
        })
        return apiUser
    }

    public async update(id: number, apiUser: ApiUser): Promise<UpdateResult> {
        try {
            const apiUsers = await this.apiUserRepository.update(
                {
                    id: +id
                },
                { ...apiUser }
            )
            return apiUsers
        } catch (err) {
            throw new BadRequestException('api user not updated')
        }
    }

    public async delete(id: number): Promise<void> {
        const apiUsers = await this.findById(id)
        await this.apiUserRepository.remove(apiUsers)
    }
}
