package handlers

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http/httptest"
	"os"
	"path/filepath"
	"testing"
	"time"

	"github.com/gin-gonic/gin"
	"wa-assistant/backend/models"
)

// These tests use only an in-memory database and disconnected WA instances.
// No server is started and no real WhatsApp request is sent.
func TestPublicAPIContract(t *testing.T) {
	gin.SetMode(gin.TestMode)
	t.Setenv("API_RATE_PER_MIN", "0")
	db := workflowTestDB(t)
	if err := db.AutoMigrate(&models.Broadcast{}, &models.BroadcastRecipient{}, &models.OTPCode{}); err != nil {
		t.Fatal(err)
	}
	key := "wai_contract_fixture"
	if err := db.Model(&models.Agent{}).Where("id = ?", 1).Update("api_key", key).Error; err != nil {
		t.Fatal(err)
	}
	create := func(row any) {
		t.Helper()
		if err := db.Create(row).Error; err != nil {
			t.Fatal(err)
		}
	}
	create(&models.Agent{ID: 2, TenantID: 2, Name: "Other fixture"})
	r := gin.New()
	v1 := r.Group("/api/v1", APIKeyMiddleware())
	v1.GET("/status", APIStatus)
	v1.POST("/messages", APISendMessage)
	v1.POST("/check", APICheckNumber)
	v1.GET("/groups", APIListGroups)
	v1.POST("/groups/:jid/messages", APIGroupSendMessage)
	v1.GET("/contacts", APIListContacts)
	v1.POST("/contacts", APISaveContact)
	v1.GET("/contacts/:number", APIGetContact)
	v1.PUT("/contacts/:number", APIUpdateContact)
	v1.DELETE("/contacts/:number", APIDeleteContact)
	v1.GET("/chats", APIListChats)
	v1.GET("/chats/:number/messages", APIChatMessages)
	v1.GET("/messages/:message_id/media", APIServeMessageMedia)
	v1.GET("/messages/:message_id/analysis", APIMessageAnalysis)
	v1.GET("/media/:cid", APIServeMedia)
	v1.POST("/broadcasts", APICreateBroadcast)
	v1.GET("/broadcasts", APIListBroadcasts)
	v1.GET("/broadcasts/:id", APIBroadcastStatus)
	v1.GET("/broadcasts/:id/recipients", APIBroadcastRecipients)
	v1.POST("/broadcasts/:id/cancel", APICancelBroadcast)
	v1.POST("/otp/request", APIRequestOTP)
	v1.POST("/otp/verify", APIVerifyOTP)
	request := func(method, path string, body any, want int) map[string]any {
		t.Helper()
		raw, _ := json.Marshal(body)
		req := httptest.NewRequest(method, "/api/v1"+path, bytes.NewReader(raw))
		req.Header.Set("Authorization", "Bearer "+key)
		req.Header.Set("Content-Type", "application/json")
		w := httptest.NewRecorder()
		r.ServeHTTP(w, req)
		if w.Code != want {
			t.Fatalf("%s %s: HTTP %d, want %d: %s", method, path, w.Code, want, w.Body.String())
		}
		var result map[string]any
		_ = json.Unmarshal(w.Body.Bytes(), &result)
		return result
	}

	t.Run("authentication_and_disconnected_handlers", func(t *testing.T) {
		w := httptest.NewRecorder()
		r.ServeHTTP(w, httptest.NewRequest("GET", "/api/v1/status", nil))
		if w.Code != 401 {
			t.Fatal("missing API key was accepted")
		}
		for _, header := range []string{"Authorization", "X-API-Key"} {
			w := httptest.NewRecorder()
			req := httptest.NewRequest("GET", "/api/v1/status", nil)
			req.Header.Set(header, key)
			r.ServeHTTP(w, req)
			if w.Code != 200 {
				t.Fatal("supported auth header rejected", header)
			}
		}
		if got := request("GET", "/status", nil, 200); got["connected"] != false || got["agent_id"] != float64(1) {
			t.Fatal(got)
		}
		request("POST", "/messages", map[string]any{"to": "081234567890", "text": "fixture"}, 409)
		request("POST", "/check", map[string]any{"numbers": []string{"081234567890"}}, 409)
		request("GET", "/groups", nil, 409)
		request("POST", "/groups/120363000000@g.us/messages", map[string]any{"text": "fixture"}, 409)
		request("POST", "/otp/request", map[string]any{"to": "081234567890"}, 409)
		request("POST", "/broadcasts", map[string]any{"message": "fixture", "recipients": []map[string]string{{"number": "081234567890"}}}, 400)
	})

	t.Run("contacts_upsert_partial_update_and_number_scope", func(t *testing.T) {
		create(&models.Contact{AgentID: 2, Number: "628999", Name: "Foreign"})
		request("POST", "/contacts", map[string]any{"number": "081234567890", "name": "Budi", "notes": "retain", "lead_stage": "warm"}, 200)
		got := request("PUT", "/contacts/6281234567890", map[string]any{"tags": "vip"}, 200)["data"].(map[string]any)
		if got["name"] != "Budi" || got["notes"] != "retain" || got["lead_stage_locked"] != true {
			t.Fatal(got)
		}
		request("PUT", "/contacts/6281234567890", map[string]any{"unknown": true}, 400)
		got = request("POST", "/contacts", map[string]any{"number": "081234567890"}, 200)["data"].(map[string]any)
		if got["name"] != "" || got["notes"] != "" || got["tags"] != "" {
			t.Fatal("upsert omission behavior changed", got)
		}
		request("GET", "/contacts/628999", nil, 404)
		listed := request("GET", "/contacts?limit=1", nil, 200)
		if listed["meta"].(map[string]any)["per_page"] != float64(1) {
			t.Fatal("limit alias ignored")
		}
		request("DELETE", "/contacts/6281234567890", nil, 200)
		request("DELETE", "/contacts/6281234567890", nil, 404)
	})

	t.Run("history_analysis_and_media_are_scoped", func(t *testing.T) {
		filename := filepath.Join(t.TempDir(), "media.txt")
		if err := os.WriteFile(filename, []byte("fixture media"), 0600); err != nil {
			t.Fatal(err)
		}
		create(&models.ChatHistory{ID: 81, AgentID: 1, Sender: "6281234567890", Message: "fixture", MediaType: "image", WAMsgID: "DOC-MSG", MediaPath: filename})
		create(&models.ChatHistory{ID: 82, AgentID: 2, Sender: "628999", MediaType: "image", WAMsgID: "FOREIGN-MSG", MediaPath: filename})
		got := request("GET", "/chats", nil, 200)["data"].([]any)
		if len(got) != 1 || got[0].(map[string]any)["number"] != "6281234567890" {
			t.Fatal(got)
		}
		request("GET", "/chats/081234567890/messages?per_page=999", nil, 200)
		analysis := request("GET", "/messages/DOC-MSG/analysis", nil, 200)["data"].(map[string]any)
		if analysis["status"] != "pending" || analysis["needs_human"] != false {
			t.Fatal(analysis)
		}
		request("GET", "/messages/DOC-MSG/media", nil, 200)
		request("GET", "/media/81", nil, 200)
		request("GET", "/messages/FOREIGN-MSG/analysis", nil, 404)
		request("GET", "/messages/FOREIGN-MSG/media", nil, 404)
		if got := request("GET", "/media/82", nil, 404); got != nil {
			t.Fatal("legacy media 404 unexpectedly JSON")
		}
	})

	t.Run("broadcast_statuses_and_scope", func(t *testing.T) {
		for index, status := range []string{"pending", "interrupted", "wa_restricted", "running", "resuming", "done", "failed", "cancelled", "cancel_requested"} {
			id := uint(index + 10)
			create(&models.Broadcast{ID: id, AgentID: 1, TenantID: 1, Status: status})
			code, want := 200, "cancelled"
			if status == "running" || status == "resuming" {
				want = "cancel_requested"
			}
			if status == "done" || status == "failed" || status == "cancelled" || status == "cancel_requested" {
				code = 409
			}
			got := request("POST", fmt.Sprintf("/broadcasts/%d/cancel", id), nil, code)
			if code == 200 && got["status"] != want {
				t.Fatal(status, got)
			}
		}
		create(&models.Broadcast{ID: 99, AgentID: 2, TenantID: 2})
		request("GET", "/broadcasts?status=cancelled", nil, 200)
		request("GET", "/broadcasts/10", nil, 200)
		request("GET", "/broadcasts/10/recipients", nil, 200)
		request("GET", "/broadcasts/99", nil, 404)
		request("GET", "/broadcasts/99/recipients", nil, 404)
		request("POST", "/broadcasts/99/cancel", nil, 404)
	})

	t.Run("otp_verification_false_true_and_single_use", func(t *testing.T) {
		create(&models.OTPCode{AgentID: 1, Number: "6281234567890", CodeHash: hashOTP(1, "6281234567890", "123456"), ExpiresAt: time.Now().Add(time.Minute)})
		for _, step := range []struct {
			code     string
			verified bool
		}{{"654321", false}, {"123456", true}, {"123456", false}} {
			got := request("POST", "/otp/verify", map[string]any{"to": "081234567890", "code": step.code}, 200)
			if got["verified"] != step.verified || (!step.verified && got["reason"] == nil) {
				t.Fatal(got)
			}
		}
	})
}
