import Foundation
import DiscordBM
import SwiftDotenv

@main
struct Zundamon {
    nonisolated(unsafe) static private(set) var ownID: UserSnowflake? = nil

    static func main() async throws {
        let tmp = Result { try Dotenv.configure() }
        switch (tmp) {
            case .success:
                print("Loaded .env file")
            case .failure:
                break
        }

        let token = ProcessInfo.processInfo.environment["DISCORD_TOKEN"]!

        let bot = await BotGatewayManager(token: token, intents: [.guildMessages, .messageContent])

        await withTaskGroup(of: Void.self) { taskGroup in
            taskGroup.addTask {
                await bot.connect()
                let tmp = try! await bot.client.getOwnUser()
                ownID = try! tmp.decode().id
            }

            for await event in await bot.events {
                taskGroup.addTask {
                    await EventHandler(event: event, client: bot.client).handleAsync()
                }
            }
        }
    }
}

struct EventHandler: GatewayEventHandler {
    let event: Gateway.Event
    let client: any DiscordClient

    func onMessageCreate(_ payload: Gateway.MessageCreate) async throws {
        try await MessageHandler(ctx: payload, client: client).handle()
    }

}
