package integration

import (
	"encoding/json"
	"fmt"
	"testing"

	"github.com/break/junhong_cmp_fiber/internal/model"
	"github.com/break/junhong_cmp_fiber/pkg/constants"
	"github.com/break/junhong_cmp_fiber/pkg/response"
	"github.com/break/junhong_cmp_fiber/tests/testutils/integ"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestCarrier_CRUD(t *testing.T) {
	env := integ.NewIntegrationTestEnv(t)

	var createdCarrierID uint

	t.Run("创建运营商", func(t *testing.T) {
		body := map[string]interface{}{
			"carrier_code": "TEST_CMCC_001",
			"carrier_name": "测试中国移动",
			"carrier_type": constants.CarrierTypeCMCC,
			"description":  "API集成测试创建的运营商",
		}
		jsonBody, _ := json.Marshal(body)

		resp, err := env.AsSuperAdmin().Request("POST", "/api/admin/carriers", jsonBody)
		require.NoError(t, err)
		defer resp.Body.Close()

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

		var result response.Response
		err = json.NewDecoder(resp.Body).Decode(&result)
		require.NoError(t, err)
		assert.Equal(t, 0, result.Code)

		dataMap, ok := result.Data.(map[string]interface{})
		require.True(t, ok)
		assert.Equal(t, "TEST_CMCC_001", dataMap["carrier_code"])
		assert.Equal(t, "测试中国移动", dataMap["carrier_name"])
		assert.Equal(t, constants.CarrierTypeCMCC, dataMap["carrier_type"])
		assert.Equal(t, float64(constants.StatusEnabled), dataMap["status"])

		createdCarrierID = uint(dataMap["id"].(float64))
		t.Logf("创建的运营商 ID: %d", createdCarrierID)
	})

	t.Run("创建运营商-编码重复应失败", func(t *testing.T) {
		body := map[string]interface{}{
			"carrier_code": "TEST_CMCC_001",
			"carrier_name": "重复编码测试",
			"carrier_type": constants.CarrierTypeCMCC,
		}
		jsonBody, _ := json.Marshal(body)

		resp, err := env.AsSuperAdmin().Request("POST", "/api/admin/carriers", jsonBody)
		require.NoError(t, err)
		defer resp.Body.Close()

		var result response.Response
		err = json.NewDecoder(resp.Body).Decode(&result)
		require.NoError(t, err)
		assert.NotEqual(t, 0, result.Code, "编码重复应返回错误")
	})

	t.Run("获取运营商详情", func(t *testing.T) {
		url := fmt.Sprintf("/api/admin/carriers/%d", createdCarrierID)
		resp, err := env.AsSuperAdmin().Request("GET", url, nil)
		require.NoError(t, err)
		defer resp.Body.Close()

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

		var result response.Response
		err = json.NewDecoder(resp.Body).Decode(&result)
		require.NoError(t, err)
		assert.Equal(t, 0, result.Code)

		dataMap := result.Data.(map[string]interface{})
		assert.Equal(t, "TEST_CMCC_001", dataMap["carrier_code"])
	})

	t.Run("获取不存在的运营商", func(t *testing.T) {
		resp, err := env.AsSuperAdmin().Request("GET", "/api/admin/carriers/99999", nil)
		require.NoError(t, err)
		defer resp.Body.Close()

		var result response.Response
		err = json.NewDecoder(resp.Body).Decode(&result)
		require.NoError(t, err)
		assert.NotEqual(t, 0, result.Code, "不存在的运营商应返回错误")
	})

	t.Run("更新运营商", func(t *testing.T) {
		body := map[string]interface{}{
			"carrier_name": "测试中国移动-更新",
			"description":  "更新后的描述",
		}
		jsonBody, _ := json.Marshal(body)

		url := fmt.Sprintf("/api/admin/carriers/%d", createdCarrierID)
		resp, err := env.AsSuperAdmin().Request("PUT", url, jsonBody)
		require.NoError(t, err)
		defer resp.Body.Close()

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

		var result response.Response
		err = json.NewDecoder(resp.Body).Decode(&result)
		require.NoError(t, err)
		assert.Equal(t, 0, result.Code)

		dataMap := result.Data.(map[string]interface{})
		assert.Equal(t, "测试中国移动-更新", dataMap["carrier_name"])
		assert.Equal(t, "更新后的描述", dataMap["description"])
	})

	t.Run("更新运营商状态-禁用", func(t *testing.T) {
		body := map[string]interface{}{
			"status": constants.StatusDisabled,
		}
		jsonBody, _ := json.Marshal(body)

		url := fmt.Sprintf("/api/admin/carriers/%d/status", createdCarrierID)
		resp, err := env.AsSuperAdmin().Request("PUT", url, jsonBody)
		require.NoError(t, err)
		defer resp.Body.Close()

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

		var result response.Response
		err = json.NewDecoder(resp.Body).Decode(&result)
		require.NoError(t, err)
		assert.Equal(t, 0, result.Code)

		var carrier model.Carrier
		env.RawDB().First(&carrier, createdCarrierID)
		assert.Equal(t, constants.StatusDisabled, carrier.Status)
	})

	t.Run("删除运营商", func(t *testing.T) {
		url := fmt.Sprintf("/api/admin/carriers/%d", createdCarrierID)
		resp, err := env.AsSuperAdmin().Request("DELETE", url, nil)
		require.NoError(t, err)
		defer resp.Body.Close()

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

		var result response.Response
		err = json.NewDecoder(resp.Body).Decode(&result)
		require.NoError(t, err)
		assert.Equal(t, 0, result.Code)

		var carrier model.Carrier
		err = env.RawDB().First(&carrier, createdCarrierID).Error
		assert.Error(t, err, "删除后应查不到运营商")
	})
}

func TestCarrier_List(t *testing.T) {
	env := integ.NewIntegrationTestEnv(t)

	carriers := []*model.Carrier{
		{CarrierCode: "TEST_LIST_001", CarrierName: "移动列表测试1", CarrierType: constants.CarrierTypeCMCC, Status: constants.StatusEnabled},
		{CarrierCode: "TEST_LIST_002", CarrierName: "联通列表测试", CarrierType: constants.CarrierTypeCUCC, Status: constants.StatusEnabled},
		{CarrierCode: "TEST_LIST_003", CarrierName: "电信列表测试", CarrierType: constants.CarrierTypeCTCC, Status: constants.StatusEnabled},
	}
	for _, c := range carriers {
		require.NoError(t, env.TX.Create(c).Error)
	}
	carriers[2].Status = constants.StatusDisabled
	require.NoError(t, env.TX.Save(carriers[2]).Error)

	t.Run("获取运营商列表-无过滤", func(t *testing.T) {
		resp, err := env.AsSuperAdmin().Request("GET", "/api/admin/carriers?page=1&page_size=20", nil)
		require.NoError(t, err)
		defer resp.Body.Close()

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

		var result response.Response
		err = json.NewDecoder(resp.Body).Decode(&result)
		require.NoError(t, err)
		assert.Equal(t, 0, result.Code)
	})

	t.Run("获取运营商列表-按类型过滤", func(t *testing.T) {
		resp, err := env.AsSuperAdmin().Request("GET", "/api/admin/carriers?carrier_type=CMCC", nil)
		require.NoError(t, err)
		defer resp.Body.Close()

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

		var result response.Response
		err = json.NewDecoder(resp.Body).Decode(&result)
		require.NoError(t, err)
		assert.Equal(t, 0, result.Code)
	})

	t.Run("获取运营商列表-按名称模糊搜索", func(t *testing.T) {
		resp, err := env.AsSuperAdmin().Request("GET", "/api/admin/carriers?carrier_name=联通", nil)
		require.NoError(t, err)
		defer resp.Body.Close()

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

		var result response.Response
		err = json.NewDecoder(resp.Body).Decode(&result)
		require.NoError(t, err)
		assert.Equal(t, 0, result.Code)
	})

	t.Run("获取运营商列表-按状态过滤", func(t *testing.T) {
		resp, err := env.AsSuperAdmin().Request("GET", fmt.Sprintf("/api/admin/carriers?status=%d", constants.StatusDisabled), nil)
		require.NoError(t, err)
		defer resp.Body.Close()

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

		var result response.Response
		err = json.NewDecoder(resp.Body).Decode(&result)
		require.NoError(t, err)
		assert.Equal(t, 0, result.Code)
	})

	t.Run("未认证请求应返回错误", func(t *testing.T) {
		resp, err := env.ClearAuth().Request("GET", "/api/admin/carriers", nil)
		require.NoError(t, err)
		defer resp.Body.Close()

		var result response.Response
		err = json.NewDecoder(resp.Body).Decode(&result)
		require.NoError(t, err)
		assert.NotEqual(t, 0, result.Code, "未认证请求应返回错误码")
	})
}
