package main

import (
	"database/sql"
	"encoding/json"
	"log"
	"net/http"
	"net/url"
	"os"
	"strconv"
	"time"

	"github.com/google/uuid"
	_ "github.com/jackc/pgx/v5/stdlib"
	"github.com/jmoiron/sqlx"
)

const insertSQL = `
INSERT INTO public."Gateways" (
	id, "name", description, routes, state, meta, account_id,
	"domain", created_by, modified_by, created_at, modified_at, domains
) VALUES (
	$1::uuid, 'lalit gateway', 'Untitled Gateway Description',
	'[{"id": "f8263694-245a-4c5f-8028-769bc6bd6487", "path": "/", "type": "integration", "method": "get", "description": "", "connected_services": {"id": "50b1d1a8-5fe4-4fa1-919e-99255455ba9d", "url": "https://asia-south1.api.fcz0.de/service/webhook/temporal/v1.0/c7d5096b-e8dd-4520-b1b9-0e4e01b839ab/workflows/execute/50b1d1a8-5fe4-4fa1-919e-99255455ba9d/0.0.1/webhook", "meta": {"is_async": true}, "type": "workflow"}}, {"id": "f1347d24-2dc8-44c5-94c8-6d5b74fd96bb", "path": "/products", "type": "integration", "method": "get", "description": "", "connected_services": {"id": "50b1d1a8-5fe4-4fa1-919e-99255455ba9d", "url": "https://asia-south1.api.fcz0.de/service/webhook/temporal/v1.0/c7d5096b-e8dd-4520-b1b9-0e4e01b839ab/workflows/execute/50b1d1a8-5fe4-4fa1-919e-99255455ba9d/0.0.1/webhook", "meta": {"is_async": true}, "type": "workflow"}}, {"id": "5a85d0c4-db79-4f02-91d4-17c29a68d243", "path": "/brands", "type": "integration", "method": "post", "description": "", "connected_services": {"id": "f595ed0f-dd6a-4b13-b74c-1f7a575d02e8", "url": "https://asia-south1.api.fcz0.de/service/webhook/temporal/v1.0/c7d5096b-e8dd-4520-b1b9-0e4e01b839ab/workflows/execute/f595ed0f-dd6a-4b13-b74c-1f7a575d02e8/0.0.9/webhook", "meta": {"rewrite": false, "merge_params": true, "rewrite_target": ""}, "type": "serverless"}}]'::jsonb,
	'active', '{}'::jsonb, 'f32bd51e-89c1-4a29-bb37-cc25d7aeb07c',
	'anujsahu7.app.fcz0.de', 'anujsahu@gofynd.com', 'anujsahu@gofynd.com',
	'2025-04-24 17:16:47.172', '2025-04-24 17:16:47.172',
	'{"self": "anujsahu7.app.fcz0.de", "test": null}'::jsonb
)
`

const selectSQL = `
SELECT
	id,
	"name",
	description,
	routes,
	state,
	meta,
	account_id,
	"domain",
	created_by,
	modified_by,
	created_at,
	modified_at,
	domains
FROM public."Gateways"
ORDER BY created_at DESC
LIMIT $1
`

type Server struct {
	db *sqlx.DB
}

func main() {
	// Example DSN:
	// export DATABASE_URL="postgres://user:pass@localhost:5432/dbname?sslmode=disable"
	dsn := "postgresql://root:root@127.0.0.1:6433/anujt11_632cfecb9b0a?sslmode=disable"
	
	// dsn = addDSNParam(dsn, "prefer_simple_protocol", "true")

	db, err := sqlx.Connect("pgx", dsn)
	if err != nil {
		log.Fatalf("db connect failed: %v", err)
	}
	defer db.Close()

	s := &Server{db: db}

	mux := http.NewServeMux()
	mux.HandleFunc("/api/insert", s.handleInsertGateways)
	mux.HandleFunc("/api/select", s.handleSelectGateways)
	mux.HandleFunc("/api/health", s.handleHealth)

	addr := ":8080"
	log.Printf("listening on %s", addr)
	if err := http.ListenAndServe(addr, withJSONHeaders(mux)); err != nil {
		log.Fatalf("server failed: %v", err)
	}
}

func (s *Server) handleInsertGateways(w http.ResponseWriter, r *http.Request) {
	count := parseIntQuery(r, "count", 1)
	if count < 1 {
		count = 1
	}
	if count > 2000 {
		count = 2000
	}

	resp := map[string]any{
		"requestedCount": count,
		"successCount":   0,
		"failureCount":   0,
		"message":        "Insert operation completed",
	}

	success := 0
	failure := 0

	// Optional: wrap in a transaction for speed when count is large
	tx, err := s.db.BeginTxx(r.Context(), &sql.TxOptions{})
	if err != nil {
		writeJSON(w, http.StatusInternalServerError, map[string]any{"error": err.Error()})
		return
	}
	defer func() {
		_ = tx.Rollback()
	}()

	for i := 0; i < count; i++ {
		id := uuid.New().String()
		if _, err := tx.ExecContext(r.Context(), insertSQL, id); err != nil {
			failure++
			log.Printf("error inserting row: %v", err)
			// keep going like your Java code (commented try/catch)
			continue
		}
		success++
	}

	if err := tx.Commit(); err != nil {
		writeJSON(w, http.StatusInternalServerError, map[string]any{"error": err.Error()})
		return
	}

	resp["successCount"] = success
	resp["failureCount"] = failure
	writeJSON(w, http.StatusOK, resp)
}

func (s *Server) handleSelectGateways(w http.ResponseWriter, r *http.Request) {
	count := parseIntQuery(r, "count", 10)
	if count < 1 {
		count = 1
	}
	if count > 200 {
		count = 200
	}

	rows, err := s.db.QueryxContext(r.Context(), selectSQL, count)
	if err != nil {
		writeJSON(w, http.StatusInternalServerError, map[string]any{"error": err.Error()})
		return
	}
	defer rows.Close()

	out := make([]map[string]any, 0, count)
	for rows.Next() {
		m := map[string]any{}
		if err := rows.MapScan(m); err != nil {
			writeJSON(w, http.StatusInternalServerError, map[string]any{"error": err.Error()})
			return
		}

		// Optional: make JSON nicer (pq returns []byte for some types)
		for k, v := range m {
			if b, ok := v.([]byte); ok {
				m[k] = string(b)
			}
		}

		out = append(out, m)
	}
	if err := rows.Err(); err != nil {
		writeJSON(w, http.StatusInternalServerError, map[string]any{"error": err.Error()})
		return
	}

	resp := map[string]any{
		"requestedCount": count,
		"returnedCount":  len(out),
		"rows":           out,
	}
	writeJSON(w, http.StatusOK, resp)
}


func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
	writeJSON(w, http.StatusOK, map[string]string{
		"status":  "UP",
		"message": "Service is running",
	})
}

// --- helpers ---

func withJSONHeaders(next http.Handler) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
		next.ServeHTTP(w, r)
	}
}

func writeJSON(w http.ResponseWriter, status int, v any) {
	w.WriteHeader(status)
	enc := json.NewEncoder(w)
	enc.SetEscapeHTML(false)
	_ = enc.Encode(v)
}

func parseIntQuery(r *http.Request, key string, def int) int {
	raw := r.URL.Query().Get(key)
	if raw == "" {
		return def
	}
	n, err := strconv.Atoi(raw)
	if err != nil {
		return def
	}
	return n
}

func mustGetEnv(key string) string {
	v := getenv(key)
	if v == "" {
		log.Fatalf("missing env var: %s", key)
	}
	return v
}

var getenv = os.Getenv

func addDSNParam(dsn, key, value string) string {
	u, err := url.Parse(dsn)
	if err != nil {
		return dsn
	}
	q := u.Query()
	if q.Get(key) == "" {
		q.Set(key, value)
	}
	u.RawQuery = q.Encode()
	return u.String()
}

// normalizeSQLTypes makes JSON output nicer for common DB driver types
// (e.g., []byte -> string, time.Time stays time.Time which json encodes as RFC3339).
func normalizeSQLTypes(rows []map[string]any) []map[string]any {
	out := make([]map[string]any, 0, len(rows))
	for _, row := range rows {
		nrow := make(map[string]any, len(row))
		for k, v := range row {
			switch t := v.(type) {
			case []byte:
				nrow[k] = string(t)
			case time.Time:
				nrow[k] = t
			default:
				nrow[k] = v
			}
		}
		out = append(out, nrow)
	}
	return out
}
