import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import SignInRecord from 'App/Models/SignInRecord'
import { DateTime } from 'luxon'
import { addDays, format, startOfDay, endOfDay } from 'date-fns'
import Decimal from 'decimal.js'
import UserBalanceService from 'App/Services/UserBalanceService'
import { BalanceRecordType } from 'App/Models/BalanceRecord'

export default class SignInRecordsController {
    public async index({ auth }: HttpContextContract) {
        const start = startOfDay(addDays(new Date(), -1))
        const end = endOfDay(addDays(new Date(), 6))
        const records = await SignInRecord.query()
            .where('date', '>=', start)
            .where('date', '<=', end)
            .where('user_id', auth.user!.id)
        const res: any[] = []
        for (let i = 0; i < 7; i++) {
            const date = addDays(start, i)
            const record = records.find(
                (record) => record.date.toISODate() === DateTime.fromJSDate(date).toISODate()
            )
            res.push({
                date: format(date, 'yyyy-MM-dd'),
                reward: record?.reward ?? new Decimal(10),
                isSigned: !!record
            })
        }
        return res
    }

    public async store({ request, auth }: HttpContextContract) {
        const record = await SignInRecord.query()
            .where('date', DateTime.now().toISODate())
            .where('user_id', auth.user!.id)
            .first()
        if (record) {
            throw new Error('今天已经签到过了')
        }
        const signInRecord = await SignInRecord.create({
            date: DateTime.now(),
            userId: auth.user!.id,
            reward: new Decimal(10)
        })
        await UserBalanceService.modifiyBalance({
            userId: auth.user!.id,
            amount: signInRecord.reward,
            type: BalanceRecordType.Reward,
            description: '签到奖励'
        })
        return signInRecord
    }
}
