import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { AliyunService } from '../aliyun/aliyun.service'
import { SmsRecord } from './entities/sms.entity'
import { Repository } from 'typeorm'
import { SendCodeDto } from './dto/sms.dto'

@Injectable()
export class SmsService {
    constructor(
        private readonly aliyunService: AliyunService,
        @InjectRepository(SmsRecord)
        private readonly smsRecordRepo: Repository<SmsRecord>
    ) {}

    public async sendVerify(data: SendCodeDto) {
        let res = await this.aliyunService.sendCode(data)
        const smsRecord = new SmsRecord()
        smsRecord.phone = data.phone
        smsRecord.code = res.code
        smsRecord.expireAt = new Date(Date.now() + 5 * 60 * 1000)
        await this.smsRecordRepo.save(smsRecord)
    }
    
    public async verify(phone: string, code: string) {
        const smsRecord = await this.smsRecordRepo.findOneBy({
            phone: phone,
            code: code
        })
        if (!smsRecord) {
            return false
        }
        if (smsRecord.expireAt < new Date()) {
            return false
        }
        return true
    }
}
