package integration

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

	"github.com/break/junhong_cmp_fiber/internal/model"
	"github.com/break/junhong_cmp_fiber/internal/model/dto"
	"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 uniqueEDTestPrefix() string {
	return fmt.Sprintf("ED%d", time.Now().UnixNano()%1000000000)
}

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

	prefix := uniqueEDTestPrefix()
	shop := env.CreateTestShop(prefix+"_SHOP", 1, nil)
	enterprise := env.CreateTestEnterprise(prefix+"_ENTERPRISE", &shop.ID)

	device1 := &model.Device{
		DeviceNo:   prefix + "_D001",
		DeviceName: "测试设备1",
		Status:     2,
		ShopID:     &shop.ID,
	}
	device2 := &model.Device{
		DeviceNo:   prefix + "_D002",
		DeviceName: "测试设备2",
		Status:     2,
		ShopID:     &shop.ID,
	}
	require.NoError(t, env.TX.Create(device1).Error)
	require.NoError(t, env.TX.Create(device2).Error)

	carrier := &model.Carrier{CarrierName: "测试运营商", CarrierType: "CMCC", Status: 1}
	require.NoError(t, env.TX.Create(carrier).Error)

	card := &model.IotCard{ICCID: prefix + "0001", CardType: "normal", CarrierID: carrier.ID, Status: 2, ShopID: &shop.ID}
	require.NoError(t, env.TX.Create(card).Error)

	now := time.Now()
	binding := &model.DeviceSimBinding{DeviceID: device1.ID, IotCardID: card.ID, SlotPosition: 1, BindStatus: 1, BindTime: &now}
	require.NoError(t, env.TX.Create(binding).Error)

	t.Run("成功授权设备给企业", func(t *testing.T) {
		reqBody := dto.AllocateDevicesReq{
			DeviceNos: []string{device1.DeviceNo},
			Remark:    "集成测试授权",
		}
		body, _ := json.Marshal(reqBody)

		url := fmt.Sprintf("/api/admin/enterprises/%d/allocate-devices", enterprise.ID)
		resp, err := env.AsSuperAdmin().Request("POST", url, body)
		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)

		data := result.Data.(map[string]interface{})
		assert.Equal(t, float64(1), data["success_count"])
		assert.Equal(t, float64(0), data["fail_count"])
	})

	t.Run("设备不存在时记录失败", func(t *testing.T) {
		reqBody := dto.AllocateDevicesReq{
			DeviceNos: []string{"NOT_EXIST_DEVICE"},
		}
		body, _ := json.Marshal(reqBody)

		url := fmt.Sprintf("/api/admin/enterprises/%d/allocate-devices", enterprise.ID)
		resp, err := env.AsSuperAdmin().Request("POST", url, body)
		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)

		data := result.Data.(map[string]interface{})
		assert.Equal(t, float64(0), data["success_count"])
		assert.Equal(t, float64(1), data["fail_count"])
	})

	t.Run("企业不存在返回错误", func(t *testing.T) {
		reqBody := dto.AllocateDevicesReq{
			DeviceNos: []string{device2.DeviceNo},
		}
		body, _ := json.Marshal(reqBody)

		resp, err := env.AsSuperAdmin().Request("POST", "/api/admin/enterprises/99999/allocate-devices", body)
		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)
	})
}

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

	prefix := uniqueEDTestPrefix()
	shop := env.CreateTestShop(prefix+"_SHOP", 1, nil)
	enterprise := env.CreateTestEnterprise(prefix+"_ENTERPRISE", &shop.ID)

	device := &model.Device{
		DeviceNo:   prefix + "_D001",
		DeviceName: "测试设备",
		Status:     2,
		ShopID:     &shop.ID,
	}
	require.NoError(t, env.TX.Create(device).Error)

	now := time.Now()
	deviceAuth := &model.EnterpriseDeviceAuthorization{
		EnterpriseID:   enterprise.ID,
		DeviceID:       device.ID,
		AuthorizedBy:   1,
		AuthorizedAt:   now,
		AuthorizerType: constants.UserTypePlatform,
	}
	require.NoError(t, env.TX.Create(deviceAuth).Error)

	t.Run("成功撤销设备授权", func(t *testing.T) {
		reqBody := dto.RecallDevicesReq{
			DeviceNos: []string{device.DeviceNo},
		}
		body, _ := json.Marshal(reqBody)

		url := fmt.Sprintf("/api/admin/enterprises/%d/recall-devices", enterprise.ID)
		resp, err := env.AsSuperAdmin().Request("POST", url, body)
		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)

		data := result.Data.(map[string]interface{})
		assert.Equal(t, float64(1), data["success_count"])
	})

	t.Run("设备未授权时返回失败", func(t *testing.T) {
		reqBody := dto.RecallDevicesReq{
			DeviceNos: []string{prefix + "_D002"},
		}
		body, _ := json.Marshal(reqBody)

		url := fmt.Sprintf("/api/admin/enterprises/%d/recall-devices", enterprise.ID)
		resp, err := env.AsSuperAdmin().Request("POST", url, body)
		require.NoError(t, err)
		defer resp.Body.Close()

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

		data := result.Data.(map[string]interface{})
		assert.Equal(t, float64(0), data["success_count"])
		assert.Equal(t, float64(1), data["fail_count"])
	})
}

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

	prefix := uniqueEDTestPrefix()
	shop := env.CreateTestShop(prefix+"_SHOP", 1, nil)
	enterprise := env.CreateTestEnterprise(prefix+"_ENTERPRISE", &shop.ID)

	devices := make([]*model.Device, 3)
	for i := 0; i < 3; i++ {
		devices[i] = &model.Device{
			DeviceNo:   fmt.Sprintf("%s_D%03d", prefix, i+1),
			DeviceName: fmt.Sprintf("测试设备%d", i+1),
			Status:     2,
			ShopID:     &shop.ID,
		}
		require.NoError(t, env.TX.Create(devices[i]).Error)
	}

	now := time.Now()
	for _, device := range devices[:2] {
		auth := &model.EnterpriseDeviceAuthorization{
			EnterpriseID:   enterprise.ID,
			DeviceID:       device.ID,
			AuthorizedBy:   1,
			AuthorizedAt:   now,
			AuthorizerType: constants.UserTypePlatform,
		}
		require.NoError(t, env.TX.Create(auth).Error)
	}

	t.Run("获取企业授权设备列表", func(t *testing.T) {
		url := fmt.Sprintf("/api/admin/enterprises/%d/devices?page=1&page_size=10", enterprise.ID)
		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)

		data := result.Data.(map[string]interface{})
		assert.Equal(t, float64(2), data["total"])
	})

	t.Run("分页查询", func(t *testing.T) {
		url := fmt.Sprintf("/api/admin/enterprises/%d/devices?page=1&page_size=1", enterprise.ID)
		resp, err := env.AsSuperAdmin().Request("GET", url, 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.Equal(t, 0, result.Code)

		data := result.Data.(map[string]interface{})
		items := data["items"].([]interface{})
		assert.Len(t, items, 1)
	})
}
