package controllers

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/gin-gonic/gin"
	"github.com/stretchr/testify/assert"

	"gitlab.com/pactual1/backend/config"
	"gitlab.com/pactual1/backend/shared"
)

// Assume setupServer() returns your gin.Engine instance
func runTestServer() *httptest.Server {
	// Initialize your database or any other setup
	// For the sake of this example, I'll just return the Gin engine

	// LOAD APPLICATION CONFIGURATION
	err := config.Load()
	if err != nil {
		log.Fatal(err)
	}

	shared.Init()
	r := gin.Default()
	r.POST("/device_info", SaveDeviceInfo)
	return httptest.NewServer(r)
}

func TestSaveDeviceInfofunc(t *testing.T) {
	ts := runTestServer()
	defer ts.Close()
	defer shared.CloseDb()

	t.Run("it should return 400 when JSON payload is invalid", func(t *testing.T) {
		payload := []byte(`{"InvalidPayload": `)
		resp, err := http.Post(fmt.Sprintf("%s/device_info", ts.URL), "application/json", bytes.NewBuffer(payload))

		if err != nil {
			t.Fatalf("Expected no error, got %v", err)
		}

		assert.Equal(t, 400, resp.StatusCode)
	})

	t.Run("it should log a message when IMEI is not found", func(t *testing.T) {
		// Add a valid payload but with an unknown IMEI
		payload := []byte(`{"IMEI": "UNKNOWN", "SomeOtherField": "Value"}`)
		resp, err := http.Post(fmt.Sprintf("%s/device_info", ts.URL), "application/json", bytes.NewBuffer(payload))

		if err != nil {
			t.Fatalf("Expected no error, got %v", err)
		}

		assert.Equal(t, 200, resp.StatusCode)
	})

	t.Run("it should return 200 when all conditions are correct", func(t *testing.T) {
		// Add a valid payload
		deviceInfo := map[string]interface{}{
			"IMEI":           "SOME_VALID_IMEI",
			"SomeOtherField": "Value",
		}

		payload, _ := json.Marshal(deviceInfo)
		resp, err := http.Post(fmt.Sprintf("%s/device_info", ts.URL), "application/json", bytes.NewBuffer(payload))

		if err != nil {
			t.Fatalf("Expected no error, got %v", err)
		}

		assert.Equal(t, 200, resp.StatusCode)
	})
}
