package main

import (
	"database/sql"
	"fmt"
	"log"
	"net/http"
	"os"

	"github.com/go-sql-driver/mysql"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
)

var db *sql.DB

type EmojiCount struct {
	Emoji      string
	TotalCount int
}

func main() {
	cfg := mysql.Config{
		User:   os.Getenv("DBUSER"),
		Passwd: os.Getenv("DBPASS"),
		Net:    "tcp",
		Addr:   "127.0.0.1:3306",
		DBName: "emojis",
	}
	// Get a database handle.
	var err error
	db, err = sql.Open("mysql", cfg.FormatDSN())
	if err != nil {
		log.Fatal(err)
	}

	pingErr := db.Ping()
	if pingErr != nil {
		log.Fatal(pingErr)
	}
	fmt.Println("Connected!")

	r := gin.Default()
	r.LoadHTMLGlob("templates/*")

	corsConfig := cors.DefaultConfig()
	corsConfig.AllowOrigins = []string{"*"}
	corsConfig.AllowHeaders = []string{"hx-current-url", "hx-request"}
	r.Use(cors.New(corsConfig))

	r.GET("/forms/emoji", func(c *gin.Context) {
		postId := c.Query("postId")
		var results []EmojiCount
		rows, err := db.Query("SELECT emoji, COUNT(*) FROM emoji_clicks WHERE post_id = ? GROUP BY emoji;", postId)
		if err != nil {
			c.HTML(http.StatusOK, "emoji_form.tmpl", gin.H{"error": err.Error(), "postId": postId})
			return
		}
		defer rows.Close()

		for rows.Next() {
			var ec EmojiCount
			if err := rows.Scan(&ec.Emoji, &ec.TotalCount); err != nil {
				c.HTML(http.StatusOK, "emoji_form.tmpl", gin.H{"error": "error getting emoji rows", "postId": postId})
				return
			}
			results = append(results, ec)
		}

		c.HTML(http.StatusOK, "emoji_form.tmpl", gin.H{
			"postId":  c.Query("postId"),
			"results": results,
		})
	})

	r.POST("/forms/emoji/post", func(c *gin.Context) {
		postId := c.PostForm("postId")
		emoji := c.PostForm("emojiInput")

		if postId == "" || emoji == "" {
			c.HTML(http.StatusOK, "emoji_form.tmpl", gin.H{"error": "missing parameters", "postId": postId})
			return
		}

		_, err := db.Exec("INSERT INTO emoji_clicks (post_id, emoji) VALUES (?, ?)", postId, emoji)
		if err != nil {
			c.HTML(http.StatusOK, "emoji_form.tmpl", gin.H{"error": "error writing to database", "postId": postId})
			return
		}

		var results []EmojiCount
		rows, err := db.Query("SELECT emoji, COUNT(*) FROM emoji_clicks WHERE post_id = ? GROUP BY emoji;", postId)
		if err != nil {
			c.HTML(http.StatusOK, "emoji_form.tmpl", gin.H{"error": err.Error(), "postId": postId})
			return
		}
		defer rows.Close()

		for rows.Next() {
			var ec EmojiCount
			if err := rows.Scan(&ec.Emoji, &ec.TotalCount); err != nil {
				c.HTML(http.StatusOK, "emoji_form.tmpl", gin.H{"error": "error getting emoji rows", "postId": postId})
				return
			}
			results = append(results, ec)
		}

		c.HTML(http.StatusOK, "emoji_form.tmpl", gin.H{"postId": postId, "results": results})
	})

	r.Run(":3001")
}
