package main

import (
	"bytes"
	"context"
	"encoding/json"
	"io"
	"net/http"
	"testing"

	"github.com/google/uuid"
	"github.com/jackc/pgx/v5/pgtype"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

// TestMediaBulkOperations tests bulk media operations
func TestMediaBulkOperations(t *testing.T) {
	setup := setupTestServer(t)

	t.Run("BulkDeleteBooks_WithoutAuth", func(t *testing.T) {
		mediaIDs := []string{uuid.New().String()}

		deleteRequest := map[string]interface{}{
			"media_item_ids": mediaIDs,
		}
		body, _ := json.Marshal(deleteRequest)

		httpReq, _ := http.NewRequest("POST", setup.Server.URL+"/api/media-items/bulk-delete", bytes.NewBuffer(body))
		httpReq.Header.Set("Content-Type", "application/json")

		client := &http.Client{}
		resp, err := client.Do(httpReq)
		require.NoError(t, err)
		defer func(Body io.ReadCloser) {
			_ = Body.Close()
		}(resp.Body)

		assert.Equal(t, http.StatusUnauthorized, resp.StatusCode)

		// NEW: Database verification
		for _, id := range mediaIDs {
			pgID, err := uuid.Parse(id)
			require.NoError(t, err, "Should parse UUID from string")

			_, dbErr := setup.DB.GetMediaItem(context.Background(), pgtype.UUID{Bytes: [16]byte(pgID), Valid: true})
			assert.Error(t, dbErr, "Media item should be deleted from database")
		}
	})

	t.Run("BulkDeleteBooks_EmptyBookIDs", func(t *testing.T) {
		req := map[string]interface{}{
			"media_item_ids": []string{},
		}
		body, _ := json.Marshal(req)

		httpReq, _ := http.NewRequest("POST", setup.Server.URL+"/api/media-items/bulk-delete", bytes.NewBuffer(body))
		httpReq.Header.Set("Content-Type", "application/json")
		httpReq.Header.Set("Authorization", "Bearer "+setup.Token)

		client := &http.Client{}
		resp, err := client.Do(httpReq)
		require.NoError(t, err)
		defer func(Body io.ReadCloser) {
			_ = Body.Close()
		}(resp.Body)

		assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
	})

	t.Run("BulkDeleteBooks_InvalidBookIDs", func(t *testing.T) {
		req := map[string]interface{}{
			"media_item_ids": []string{"invalid-uuid", "another-invalid"},
		}
		body, _ := json.Marshal(req)

		httpReq, _ := http.NewRequest("POST", setup.Server.URL+"/api/media-items/bulk-delete", bytes.NewBuffer(body))
		httpReq.Header.Set("Content-Type", "application/json")
		httpReq.Header.Set("Authorization", "Bearer "+setup.Token)

		client := &http.Client{}
		resp, err := client.Do(httpReq)
		require.NoError(t, err)
		defer func(Body io.ReadCloser) {
			_ = Body.Close()
		}(resp.Body)

		assert.Equal(t, http.StatusOK, resp.StatusCode)

		var result map[string]interface{}
		err = json.NewDecoder(resp.Body).Decode(&result)
		require.NoError(t, err)

		assert.Contains(t, result, "results")
		assert.Contains(t, result, "total")
		assert.Contains(t, result, "deleted")
		assert.Contains(t, result, "failed")
	})

	t.Run("BulkDeleteBooks_WithValidBooks", func(t *testing.T) {
		mediaID1 := createTestMediaItemID(t, setup)
		mediaID2 := createTestMediaItemID(t, setup)
		mediaID3 := uuid.New().String()

		req := map[string]interface{}{
			"media_item_ids": []string{mediaID1, mediaID2, mediaID3},
		}
		body, _ := json.Marshal(req)

		httpReq, _ := http.NewRequest("POST", setup.Server.URL+"/api/media-items/bulk-delete", bytes.NewBuffer(body))
		httpReq.Header.Set("Content-Type", "application/json")
		httpReq.Header.Set("Authorization", "Bearer "+setup.Token)

		client := &http.Client{}
		resp, err := client.Do(httpReq)
		require.NoError(t, err)
		defer func(Body io.ReadCloser) {
			_ = Body.Close()
		}(resp.Body)

		assert.Equal(t, http.StatusOK, resp.StatusCode)

		var result map[string]interface{}
		err = json.NewDecoder(resp.Body).Decode(&result)
		require.NoError(t, err)

		assert.Contains(t, result, "results")
		assert.Equal(t, 3.0, result["total"])
		// Check that deleted field exists and has at least 2 (the valid books)
		if deleted, ok := result["deleted"].(float64); ok {
			assert.True(t, deleted >= 2, "Should delete at least valid books")
		}
	})

	t.Run("BulkDeleteBooks_InvalidRequestBody", func(t *testing.T) {
		// Send invalid JSON
		httpReq, _ := http.NewRequest("POST", setup.Server.URL+"/api/media-items/bulk-delete", bytes.NewBuffer([]byte("invalid json")))
		httpReq.Header.Set("Content-Type", "application/json")
		httpReq.Header.Set("Authorization", "Bearer "+setup.Token)

		client := &http.Client{}
		resp, err := client.Do(httpReq)
		require.NoError(t, err)
		defer func(Body io.ReadCloser) {
			_ = Body.Close()
		}(resp.Body)

		assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
	})

	t.Run("BulkUpdateBooks_WithoutAuth", func(t *testing.T) {
		req := map[string]interface{}{
			"media_item_updates": []map[string]interface{}{
				{
					"media_item_id": uuid.New().String(),
					"updates": map[string]interface{}{
						"tags": []string{"test"},
					},
				},
			},
		}
		body, _ := json.Marshal(req)

		httpReq, _ := http.NewRequest("POST", setup.Server.URL+"/api/media-items/bulk-update", bytes.NewBuffer(body))
		httpReq.Header.Set("Content-Type", "application/json")

		client := &http.Client{}
		resp, err := client.Do(httpReq)
		require.NoError(t, err)
		defer func(Body io.ReadCloser) {
			_ = Body.Close()
		}(resp.Body)

		assert.Equal(t, http.StatusUnauthorized, resp.StatusCode)
	})

	t.Run("BulkUpdateBooks_EmptyBookIDs", func(t *testing.T) {
		req := map[string]interface{}{
			"media_item_updates": []map[string]interface{}{
				{
					"media_item_id": "",
					"updates": map[string]interface{}{
						"tags": []string{"test"},
					},
				},
			},
		}
		body, _ := json.Marshal(req)

		httpReq, _ := http.NewRequest("POST", setup.Server.URL+"/api/media-items/bulk-update", bytes.NewBuffer(body))
		httpReq.Header.Set("Content-Type", "application/json")
		httpReq.Header.Set("Authorization", "Bearer "+setup.Token)

		client := &http.Client{}
		resp, err := client.Do(httpReq)
		require.NoError(t, err)
		defer func(Body io.ReadCloser) {
			_ = Body.Close()
		}(resp.Body)

		assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
	})

	t.Run("BulkUpdateBooks_InvalidBookIDs", func(t *testing.T) {
		req := map[string]interface{}{
			"media_item_updates": []map[string]interface{}{
				{
					"media_item_id": "invalid-uuid",
					"updates": map[string]interface{}{
						"tags": []string{"fiction", "test"},
					},
				},
			},
		}
		body, _ := json.Marshal(req)

		httpReq, _ := http.NewRequest("POST", setup.Server.URL+"/api/media-items/bulk-update", bytes.NewBuffer(body))
		httpReq.Header.Set("Content-Type", "application/json")
		httpReq.Header.Set("Authorization", "Bearer "+setup.Token)

		client := &http.Client{}
		resp, err := client.Do(httpReq)
		require.NoError(t, err)
		defer func(Body io.ReadCloser) {
			_ = Body.Close()
		}(resp.Body)

		assert.Equal(t, http.StatusOK, resp.StatusCode)

		var result map[string]interface{}
		err = json.NewDecoder(resp.Body).Decode(&result)
		require.NoError(t, err)

		assert.Contains(t, result, "results")
		assert.Contains(t, result, "total")
		assert.Contains(t, result, "updated")
		assert.Contains(t, result, "failed")
	})

	t.Run("BulkUpdateBooks_UpdateTags", func(t *testing.T) {
		mediaID1 := createTestMediaItemID(t, setup)
		mediaID2 := createTestMediaItemID(t, setup)

		req := map[string]interface{}{
			"media_item_updates": []map[string]interface{}{
				{
					"media_item_id": mediaID1,
					"updates": map[string]interface{}{
						"tags": []string{"fiction", "science-fiction", "test"},
					},
				},
				{
					"media_item_id": mediaID2,
					"updates": map[string]interface{}{
						"tags": []string{"fiction", "science-fiction", "test"},
					},
				},
			},
		}
		body, _ := json.Marshal(req)

		httpReq, _ := http.NewRequest("POST", setup.Server.URL+"/api/media-items/bulk-update", bytes.NewBuffer(body))
		httpReq.Header.Set("Content-Type", "application/json")
		httpReq.Header.Set("Authorization", "Bearer "+setup.Token)

		client := &http.Client{}
		resp, err := client.Do(httpReq)
		require.NoError(t, err)
		defer func(Body io.ReadCloser) {
			_ = Body.Close()
		}(resp.Body)

		assert.Equal(t, http.StatusOK, resp.StatusCode)

		var result map[string]interface{}
		err = json.NewDecoder(resp.Body).Decode(&result)
		require.NoError(t, err)

		assert.Contains(t, result, "results")
		assert.Equal(t, 2.0, result["total"])
		// Check that updated field exists and has at least 1
		if updated, ok := result["updated"].(float64); ok {
			assert.True(t, updated > 0, "Should update at least one book")
		}
	})

	t.Run("BulkUpdateBooks_UpdateReadingStatus", func(t *testing.T) {
		mediaID1 := createTestMediaItemID(t, setup)
		mediaID2 := createTestMediaItemID(t, setup)
		mediaID3 := createTestMediaItemID(t, setup)
		mediaID4 := createTestMediaItemID(t, setup)

		req := map[string]interface{}{
			"media_item_updates": []map[string]interface{}{
				{
					"media_item_id": mediaID1,
					"updates": map[string]interface{}{
						"reading_status": "reading",
					},
				},
				{
					"media_item_id": mediaID2,
					"updates": map[string]interface{}{
						"reading_status": "reading",
					},
				},
				{
					"media_item_id": mediaID3,
					"updates": map[string]interface{}{
						"reading_status": "to-read",
					},
				},
				{
					"media_item_id": mediaID4,
					"updates": map[string]interface{}{
						"reading_status": "did-not-finish",
					},
				},
			},
		}
		body, _ := json.Marshal(req)

		httpReq, _ := http.NewRequest("POST", setup.Server.URL+"/api/media-items/bulk-update", bytes.NewBuffer(body))
		httpReq.Header.Set("Content-Type", "application/json")
		httpReq.Header.Set("Authorization", "Bearer "+setup.Token)

		client := &http.Client{}
		resp, err := client.Do(httpReq)
		require.NoError(t, err)
		defer func(Body io.ReadCloser) {
			_ = Body.Close()
		}(resp.Body)

		assert.Equal(t, http.StatusOK, resp.StatusCode)

		var result map[string]interface{}
		err = json.NewDecoder(resp.Body).Decode(&result)
		require.NoError(t, err)

		assert.Contains(t, result, "results")
		assert.Contains(t, result, "total")
		assert.Equal(t, 4.0, result["total"])

		// NEW: Verify database state
		for _, mediaID := range []string{mediaID1, mediaID2, mediaID3, mediaID4} {
			parsedID, err := uuid.Parse(mediaID)
			require.NoError(t, err, "Should parse media ID UUID")
			pgID := pgtype.UUID{Bytes: [16]byte(parsedID), Valid: true}
			item, err := setup.DB.GetMediaItem(context.Background(), pgID)
			assert.NoError(t, err, "Should retrieve media item")

			// Verify the item was created successfully
			assert.True(t, item.ID.Valid, "Media item should have valid ID")
		}
	})

	t.Run("BulkUpdateBooks_UpdateMultipleFields", func(t *testing.T) {
		mediaID1 := createTestMediaItemID(t, setup)

		req := map[string]interface{}{
			"media_item_updates": []map[string]interface{}{
				{
					"media_item_id": mediaID1,
					"updates": map[string]interface{}{
						"tags":           []string{"test", "bulk-update"},
						"reading_status": "to-read",
						"rating":         4,
					},
				},
			},
		}
		body, _ := json.Marshal(req)

		httpReq, _ := http.NewRequest("POST", setup.Server.URL+"/api/media-items/bulk-update", bytes.NewBuffer(body))
		httpReq.Header.Set("Content-Type", "application/json")
		httpReq.Header.Set("Authorization", "Bearer "+setup.Token)

		client := &http.Client{}
		resp, err := client.Do(httpReq)
		require.NoError(t, err)
		defer func(Body io.ReadCloser) {
			_ = Body.Close()
		}(resp.Body)

		assert.Equal(t, http.StatusOK, resp.StatusCode)

		var result map[string]interface{}
		err = json.NewDecoder(resp.Body).Decode(&result)
		require.NoError(t, err)

		assert.Contains(t, result, "results")
	})

	t.Run("BulkUpdateBooks_InvalidRequestBody", func(t *testing.T) {
		// Send invalid JSON
		httpReq, _ := http.NewRequest("POST", setup.Server.URL+"/api/media-items/bulk-update", bytes.NewBuffer([]byte("invalid json")))
		httpReq.Header.Set("Content-Type", "application/json")
		httpReq.Header.Set("Authorization", "Bearer "+setup.Token)

		client := &http.Client{}
		resp, err := client.Do(httpReq)
		require.NoError(t, err)
		defer func(Body io.ReadCloser) {
			_ = Body.Close()
		}(resp.Body)

		assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
	})
}
