package tasks

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

	"github.com/gin-gonic/gin"
	"github.com/glebarez/sqlite"
	"github.com/stretchr/testify/require"
	"gorm.io/gorm"
	"senlinai-agent/backend/internal/config"
	"senlinai-agent/backend/internal/httpx"
	"senlinai-agent/backend/internal/models"
)

func TestTaskRegistrarCreatesIdentityDTOForOwnedProject(t *testing.T) {
	router, database, project := newTaskHandlerTestRouter(t, 1)
	body := bytes.NewBufferString(`{"title":"整理访谈","description":"提取行动项","dueAt":"2026-07-22T08:00:00Z","tag":"客户"}`)
	req := httptest.NewRequest(http.MethodPost, "/api/v1/projects/"+project.Identity+"/tasks", body)
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer test-token")
	rec := httptest.NewRecorder()

	router.ServeHTTP(rec, req)

	require.Equal(t, http.StatusCreated, rec.Code, rec.Body.String())
	var task models.SenlinAgentTask
	require.NoError(t, database.Where("project_id = ?", project.ID).First(&task).Error)
	var payload map[string]any
	require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &payload))
	require.Equal(t, task.Identity, payload["id"])
	require.Equal(t, project.Identity, payload["projectId"])
	require.Equal(t, "客户", payload["tag"])
	require.NotEmpty(t, payload["tagId"])
	require.NotEmpty(t, payload["createdAt"])
	require.NotContains(t, payload, "ID")
	require.NotContains(t, payload, "ProjectID")
}

func TestTaskRegistrarMovesTaskByIdentityAndClearsForeignProjectTag(t *testing.T) {
	router, database, first := newTaskHandlerTestRouter(t, 1)
	second := models.SenlinAgentProject{OwnerID: 1, Name: "Beta", Identifier: "BETA"}
	require.NoError(t, database.Create(&second).Error)
	tag := models.SenlinAgentTag{ProjectID: first.ID, Name: "仅 Alpha"}
	require.NoError(t, database.Create(&tag).Error)
	task := models.SenlinAgentTask{ProjectID: first.ID, CreatedBy: 1, TagID: &tag.ID, Title: "迁移任务", Status: "open"}
	require.NoError(t, database.Create(&task).Error)
	note := models.SenlinAgentNote{ProjectID: first.ID, CreatedBy: 1, Title: "旧项目资料", Markdown: "仅可在 Alpha 分享"}
	require.NoError(t, database.Create(&note).Error)
	require.NoError(t, NewService(database).ShareObject(task.ID, "note", note.ID))
	body := bytes.NewBufferString(fmt.Sprintf(`{"title":"迁移任务","description":"已移动","completed":false,"nextProjectId":%q}`, strings.ToUpper(second.Identity)))
	req := httptest.NewRequest(http.MethodPatch, "/api/v1/projects/"+first.Identity+"/tasks/"+task.Identity, body)
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer test-token")
	rec := httptest.NewRecorder()

	router.ServeHTTP(rec, req)

	require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
	require.NoError(t, database.First(&task, task.ID).Error)
	require.Equal(t, second.ID, task.ProjectID)
	require.Nil(t, task.TagID)
	var shareCount int64
	require.NoError(t, database.Model(&models.SenlinAgentTaskShare{}).Where("task_id = ?", task.ID).Count(&shareCount).Error)
	require.Zero(t, shareCount, "移动项目后不能保留旧项目的显式分享")
	var payload map[string]any
	require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &payload))
	require.Equal(t, second.Identity, payload["projectId"])
	require.Nil(t, payload["tagId"])
}

func TestTaskRegistrarRejectsProjectOwnedByAnotherUser(t *testing.T) {
	router, database, _ := newTaskHandlerTestRouter(t, 1)
	other := models.SenlinAgentProject{OwnerID: 2, Name: "Private", Identifier: "PRIVATE"}
	require.NoError(t, database.Create(&other).Error)
	req := httptest.NewRequest(http.MethodPost, "/api/v1/projects/"+other.Identity+"/tasks", bytes.NewBufferString(`{"title":"越权"}`))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer test-token")
	rec := httptest.NewRecorder()

	router.ServeHTTP(rec, req)

	require.Equal(t, http.StatusNotFound, rec.Code, rec.Body.String())
	var count int64
	require.NoError(t, database.Model(&models.SenlinAgentTask{}).Where("project_id = ?", other.ID).Count(&count).Error)
	require.Zero(t, count)
}

func newTaskHandlerTestRouter(t *testing.T, currentUserID uint) (*gin.Engine, *gorm.DB, models.SenlinAgentProject) {
	t.Helper()
	database, err := gorm.Open(sqlite.Open(fmt.Sprintf("file:%s?mode=memory&cache=shared", t.Name())), &gorm.Config{TranslateError: true})
	require.NoError(t, err)
	require.NoError(t, models.AutoMigrate(database))
	models.DBService = database
	require.NoError(t, database.Create(&models.SenlinAgentUser{Email: "owner@example.com", DisplayName: "Owner", PasswordHash: "hash"}).Error)
	require.NoError(t, database.Create(&models.SenlinAgentUser{Email: "other@example.com", DisplayName: "Other", PasswordHash: "hash"}).Error)
	project := models.SenlinAgentProject{OwnerID: 1, Name: "Alpha", Identifier: "ALPHA"}
	require.NoError(t, database.Create(&project).Error)
	router := httpx.NewProtectedRouter(
		config.Config{Env: "test"},
		func(string) (uint, error) { return currentUserID, nil },
		NewHandler(NewService(database)),
	)
	return router, database, project
}
