package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/url"
	"os"

	"github.com/gorilla/websocket"
)

type Event struct {
	Type    string          `json:"type"`
	Payload json.RawMessage `json:"payload"`
}

type MemberEvent struct {
	ServerID string `json:"server_id"`
	UserID   string `json:"user_id"`
	Username string `json:"username"`
}

func main() {
	token := os.Getenv("BOT_TOKEN")
	if token == "" {
		log.Fatal("BOT_TOKEN environment variable required")
	}

	host := os.Getenv("DUMPSTER_HOST")
	if host == "" {
		host = "localhost:8080"
	}

	// Channel to send welcome messages to (set per server)
	welcomeChannels := map[string]string{
		// server_id -> channel_id
		// Configure these via env or config file
	}

	u := url.URL{
		Scheme:   "ws",
		Host:     host,
		Path:     "/ws/bot",
		RawQuery: "token=" + token,
	}

	log.Printf("Connecting to %s", u.String())

	c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
	if err != nil {
		log.Fatal("dial:", err)
	}
	defer c.Close()

	log.Println("Welcome bot connected!")

	for {
		_, message, err := c.ReadMessage()
		if err != nil {
			log.Println("read:", err)
			break
		}

		var event Event
		if err := json.Unmarshal(message, &event); err != nil {
			continue
		}

		switch event.Type {
		case "SERVER_MEMBER_ADD":
			var member MemberEvent
			if err := json.Unmarshal(event.Payload, &member); err != nil {
				continue
			}
			handleMemberJoin(c, member, welcomeChannels)
		}
	}
}

func handleMemberJoin(c *websocket.Conn, member MemberEvent, welcomeChannels map[string]string) {
	channelID, ok := welcomeChannels[member.ServerID]
	if !ok {
		log.Printf("No welcome channel configured for server %s", member.ServerID)
		return
	}

	welcomeMsg := fmt.Sprintf(
		"👋 Welcome to the server, <@%s>! Glad to have you here.\n\n"+
			"Check out the rules in #rules and introduce yourself!",
		member.UserID,
	)

	log.Printf("Sending welcome message for %s to channel %s", member.Username, channelID)
	sendMessage(c, channelID, welcomeMsg)
}

func sendMessage(c *websocket.Conn, channelID, content string) {
	msg := map[string]interface{}{
		"type": "SEND_MESSAGE",
		"payload": map[string]string{
			"channel_id": channelID,
			"content":    content,
		},
	}
	data, _ := json.Marshal(msg)
	c.WriteMessage(websocket.TextMessage, data)
}
