package handlers

import (
	"context"
	"errors"
	"fmt"
	"mime"
	"net/http/httptest"
	"os"
	"path/filepath"
	"strconv"
	"testing"

	"github.com/gin-gonic/gin"
	"go.mau.fi/whatsmeow"
	"wa-assistant/backend/models"
)

func TestInboxMediaSeparatesExpiredMediaFromTransientFailures(t *testing.T) {
	for _, tc := range []struct {
		err    error
		status int
	}{
		{fmt.Errorf("wrapped: %w", whatsmeow.ErrMediaDownloadFailedWith410), 410},
		{whatsmeow.ErrMediaDownloadFailedWith404, 410},
		{context.DeadlineExceeded, 504},
		{errors.New("WhatsApp belum terhubung"), 503},
		{errors.New("temporary network failure"), 502},
	} {
		got := inboxMediaError(tc.err)
		if got.Status != tc.status {
			t.Fatalf("%v mapped to %d instead of %d", tc.err, got.Status, tc.status)
		}
	}
}

func TestInboxMediaDownloadKeepsFilenameRangeAndAuthorization(t *testing.T) {
	db, _ := csWorkspaceDB(t)
	path := filepath.Join(t.TempDir(), "cache.mp4")
	if err := os.WriteFile(path, []byte("0123456789"), 0600); err != nil {
		t.Fatal(err)
	}
	message := models.ChatHistory{AgentID: 1, Sender: "628111111111", MediaPath: path, MediaType: "video", Mimetype: "video/mp4", FileName: "../Video pelanggan ü.mp4"}
	if err := db.Create(&message).Error; err != nil {
		t.Fatal(err)
	}
	r := gin.New()
	r.GET("/api/agents/:id/media/:cid", ServeMedia)
	url := "/api/agents/1/media/" + strconv.Itoa(int(message.ID)) + "?download=1&token=" + issueMediaToken(1, 1)
	request := httptest.NewRequest("GET", url, nil)
	request.Header.Set("Range", "bytes=2-5")
	w := httptest.NewRecorder()
	r.ServeHTTP(w, request)
	kind, params, err := mime.ParseMediaType(w.Header().Get("Content-Disposition"))
	if w.Code != 206 || w.Body.String() != "2345" || err != nil || kind != "attachment" || params["filename"] != "Video pelanggan ü.mp4" || w.Header().Get("Content-Type") != "video/mp4" {
		t.Fatalf("invalid download: %d %v %s", w.Code, w.Header(), w.Body.String())
	}
	w = httptest.NewRecorder()
	r.ServeHTTP(w, httptest.NewRequest("GET", "/api/agents/1/media/"+strconv.Itoa(int(message.ID))+"?download=1", nil))
	if w.Code != 401 {
		t.Fatal("download bypassed authentication", w.Code)
	}
	db.Model(&message).Update("revoked", true)
	w = httptest.NewRecorder()
	r.ServeHTTP(w, httptest.NewRequest("GET", url, nil))
	if w.Code != 410 {
		t.Fatal("revoked media remained downloadable", w.Code)
	}
}

func TestInboxCachedMediaBypassesDownloadQueueAndKeepsAccountScope(t *testing.T) {
	db, _ := csWorkspaceDB(t)
	path := filepath.Join(t.TempDir(), "document.txt")
	if err := os.WriteFile(path, []byte("fixture document"), 0600); err != nil {
		t.Fatal(err)
	}
	message := models.ChatHistory{AgentID: 1, Sender: "628111", MediaPath: path, MediaMetadata: []byte("unused metadata"), MediaType: "document"}
	if err := db.Create(&message).Error; err != nil {
		t.Fatal(err)
	}
	for range cap(historicalMediaSlots) {
		historicalMediaSlots <- struct{}{}
	}
	t.Cleanup(func() {
		for range cap(historicalMediaSlots) {
			<-historicalMediaSlots
		}
	})
	r := gin.New()
	r.GET("/api/agents/:id/media/:cid", ServeMedia)
	for _, tc := range []struct {
		id     string
		status int
	}{{"1", 200}, {"2", 403}} {
		w := httptest.NewRecorder()
		r.ServeHTTP(w, httptest.NewRequest("GET", "/api/agents/"+tc.id+"/media/"+strconv.Itoa(int(message.ID))+"?token="+issueMediaToken(1, 1), nil))
		if w.Code != tc.status {
			t.Fatalf("account %s returned %d, expected %d", tc.id, w.Code, tc.status)
		}
		if tc.status == 200 && w.Body.String() != "fixture document" {
			t.Fatal("cached document changed")
		}
	}
}
