import { PhoneLoginDto } from './dto/login.dto'
import { Injectable } from '@nestjs/common'
import { JwtService } from '@nestjs/jwt'
import { UsersService } from '../users/users.service'

@Injectable()
export class AuthService {
    constructor(private readonly usersService: UsersService, private readonly jwtService: JwtService) {}

    async loginByPhone(loginDto: PhoneLoginDto) {
        let user = await this.usersService.loginByPhone(loginDto.phone, loginDto.code, loginDto.invitor)
        const payload = {
            username: user.username,
            sub: user.id,
            roles: user.roles
        }
        this.usersService.updateIat(user)
        return {
            access_token: this.jwtService.sign(payload),
            user
        }
    }

    async loginAdmin(username: string, password: string) {
        let user = await this.usersService.loginAdmin(username, password)
        const payload = {
            username: user.username,
            sub: user.id,
            roles: user.roles
        }
        this.usersService.updateIat(user)
        return {
            access_token: this.jwtService.sign(payload)
        }
    }

    async getToken(id: number) {
        let user = await this.usersService.findById(id)
        const payload = {
            username: user.username,
            sub: user.id,
            roles: user.roles
        }
        return {
            access_token: this.jwtService.sign(payload)
        }
    }
}
