import {adminId, SubcommandData} from "../types.js"
import {
    ActivityType,
    ApplicationCommandOptionType,
    ApplicationCommandSubCommandData,
    ChatInputCommandInteraction,
} from "discord.js"
import {wrappedRestart} from "../../ipc/restart.js"
import {spawn} from "child_process"
import {defaultPresence} from "../../defaultPresence.js"
import {resolve as resolvePath} from "path"

class RebuildCommand extends SubcommandData {
    readonly definition: ApplicationCommandSubCommandData = {
        name: "rebuild",
        description: "Rebuilds and restarts the bot.",
        type: ApplicationCommandOptionType.Subcommand,
    }

    async execute(b: ChatInputCommandInteraction): Promise<void> {
        const user = b.user || b.member
        if (!!user && user.id === adminId) {
            await b.reply("Mmm... let's see... this goes here...")
            const self = b.client.user
            self.setPresence({
                status: "online",
                afk: false,
                activities: [
                    {
                        type: ActivityType.Watching,
                        name: "Compilers at Work",
                    },
                ],
            })
            try {
                await new Promise<void>((resolve, reject) => {
                    const result = spawn(resolvePath("./node_modules/.bin/tsc"), {
                        cwd: process.cwd(),
                        stdio: "inherit",
                        detached: true,
                        shell: true,
                    })
                    result.on("error", (ex) => {
                        reject(ex)
                    })
                    result.on("exit", (code) => {
                        if (code !== 0) {
                            reject(`Bad exit code ${code}`)
                        } else {
                            resolve()
                        }
                    })
                })
            } catch (ex) {
                console.log(ex)
                self.setPresence(defaultPresence)
                await b.followUp("Oops... I think it's broke...")
                return
            }
            self.setPresence({
                status: "idle",
                afk: true,
                activities: [
                    {
                        type: ActivityType.Listening,
                        name: "Born-Again Bot Girl",
                    },
                ],
            })
            await b.followUp("Phewwww... now I'll just... take a quick nap after all that hard work...")
            await wrappedRestart(b)
        } else {
            await b.reply("Heeey... I don't gotta do what you say...")
        }
    }
}

export const commandBotRebuild = new RebuildCommand()