/*
Copyright © 2026 NAME HERE <EMAIL ADDRESS>
*/
package cmd

import (
	"<@var(context.project.goprefix)>/<@var(context.project.name)>/config"
	"<@var(context.project.goprefix)>/<@var(context.project.name)>/db"
	"<@var(context.project.goprefix)>/<@var(context.project.name)>/server/todo"
	connectors "connectrpc.com/cors"
	"context"
	"github.com/jackc/pgx/v5/pgxpool"
	"github.com/rs/cors"
	"github.com/spf13/cobra"
	"net/http"
	"strconv"
	"strings"
)

// serveCmd represents the serve command
var serveCmd = &cobra.Command{
	Use:   "serve",
	Short: "start server",
	Long:  ``,
	RunE: func(cmd *cobra.Command, args []string) error {
		err := config.Load()
		if err != nil {
			err := config.Write(*config.DefaultConf)
			if err != nil {
				return err
			}
		}
		conf := *config.Conf
		ctx := context.Background()
		db_url := "postgres://" + conf.Database.User + ":" + conf.Database.Password + "@" + conf.Database.Host + ":" + strconv.Itoa(conf.Database.Port) + "/" + conf.Database.Name
		db_url = db_url + "?sslmode=disable"
		conn, err := pgxpool.New(ctx, db_url)
		if err != nil {
			panic(err.Error())
		}
		err = db.RunDbMigrations()
		if err != nil {
			return err
		}
		db.Q = db.New(conn)
		middleware := cors.New(cors.Options{
			AllowedOrigins: conf.Server.FrontendUrls,
			AllowedMethods: connectors.AllowedMethods(),
			AllowedHeaders: connectors.AllowedHeaders(),
			ExposedHeaders: connectors.ExposedHeaders(),
			Debug:          true,
		})
		mux := http.NewServeMux()
		todoPath, todoHandler := todo.GetPathHandler()
		mux.Handle(todoPath, todoHandler)
		p := new(http.Protocols)
		p.SetHTTP1(true)
		p.SetUnencryptedHTTP2(true)
		s := http.Server{
			Addr:      strings.Join([]string{conf.Server.Host, strconv.Itoa(conf.Server.Port)}, ":"),
			Handler:   middleware.Handler(mux),
			Protocols: p,
		}
		s.ListenAndServe()
		return nil
	},
}

func init() {
	rootCmd.AddCommand(serveCmd)

	// Here you will define your flags and configuration settings.

	// Cobra supports Persistent Flags which will work for this command
	// and all subcommands, e.g.:
	// serveCmd.PersistentFlags().String("foo", "", "A help for foo")

	// Cobra supports local flags which will only run when this command
	// is called directly, e.g.:
	// serveCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
