import Database from '@ioc:Adonis/Lucid/Database'
import Membership from 'App/Models/Membership'
import Referrer from 'App/Models/Referrer'
import User from 'App/Models/User'
import UserBalance from 'App/Models/UserBalance'
import Decimal from 'decimal.js'
import { DateTime } from 'luxon'
import randomstring from 'randomstring'
import { addDays } from 'date-fns'
class UserService {
    public async findById(id: number) {
        return await User.findByOrFail('id', id)
    }

    public async findAll() {
        return await User.query().paginate(1, 10)
    }

    public async register(data: { username?: string; password: string; email?: string }) {
        const user = new User()
        user.merge(data)
        if (!user.username) {
            user.username = 'fs_' + randomstring.generate(8)
        }
        const r = await Referrer.findBy('email', data.email)
        if (r) {
            user.referrer = r.referrer
        }
        await user.save()
        await UserBalance.create({
            userId: user.id,
            balance: new Decimal('9999')
        })

        if (r) {
            const invited = (
                await Database.from('users').where('referrer', r.referrer).count('*', 'count')
            )[0].count
            if ((invited + 1) % 3 === 0) {
                let member = await Membership.query()
                    .where('userId', r.referrer)
                    .orderBy('expireAt', 'desc')
                    .first()
                if (member && member.expireAt.toJSDate() < new Date()) {
                    member = null
                }

                const startAt = member ? member.expireAt.toJSDate() : new Date()
                const expireAt = addDays(startAt, 7)
                await Membership.create({
                    userId: r.referrer,
                    startAt: DateTime.fromJSDate(startAt),
                    expireAt: DateTime.fromJSDate(expireAt)
                })
            }
        }

        return user
    }
}
export default new UserService()
