package unit

import (
	"context"
	"fmt"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"

	"github.com/break/junhong_cmp_fiber/internal/model"
	"github.com/break/junhong_cmp_fiber/internal/model/dto"
	"github.com/break/junhong_cmp_fiber/internal/service/enterprise"
	"github.com/break/junhong_cmp_fiber/internal/store/postgres"
	"github.com/break/junhong_cmp_fiber/pkg/constants"
	"github.com/break/junhong_cmp_fiber/tests/testutils"
)

func createEnterpriseTestContext(userID uint) context.Context {
	ctx := context.Background()
	ctx = context.WithValue(ctx, constants.ContextKeyUserID, userID)
	ctx = context.WithValue(ctx, constants.ContextKeyUserType, constants.UserTypePlatform)
	return ctx
}

func TestEnterpriseService_Create(t *testing.T) {
	tx := testutils.NewTestTransaction(t)
	rdb := testutils.GetTestRedis(t)
	testutils.CleanTestRedisKeys(t, rdb)

	enterpriseStore := postgres.NewEnterpriseStore(tx, rdb)
	shopStore := postgres.NewShopStore(tx, rdb)
	accountStore := postgres.NewAccountStore(tx, rdb)

	service := enterprise.New(tx, enterpriseStore, shopStore, accountStore)

	t.Run("创建企业-含账号创建", func(t *testing.T) {
		ctx := createEnterpriseTestContext(1)

		req := &dto.CreateEnterpriseReq{
			EnterpriseName: "测试企业",
			EnterpriseCode: "ENT_TEST_001",
			ContactName:    "测试联系人",
			ContactPhone:   "13800000001",
			LoginPhone:     "13900000001",
			Password:       "Test123456",
		}

		result, err := service.Create(ctx, req)
		require.NoError(t, err)
		assert.NotNil(t, result)
		assert.Equal(t, "测试企业", result.Enterprise.EnterpriseName)
		assert.Equal(t, "ENT_TEST_001", result.Enterprise.EnterpriseCode)
		assert.Equal(t, constants.StatusEnabled, result.Enterprise.Status)
		assert.Greater(t, result.AccountID, uint(0))
	})

	t.Run("创建企业-企业编号已存在应失败", func(t *testing.T) {
		ctx := createEnterpriseTestContext(1)

		req1 := &dto.CreateEnterpriseReq{
			EnterpriseName: "企业一",
			EnterpriseCode: "ENT_DUP_001",
			ContactName:    "联系人一",
			ContactPhone:   "13800000010",
			LoginPhone:     "13900000010",
			Password:       "Test123456",
		}
		_, err := service.Create(ctx, req1)
		require.NoError(t, err)

		req2 := &dto.CreateEnterpriseReq{
			EnterpriseName: "企业二",
			EnterpriseCode: "ENT_DUP_001",
			ContactName:    "联系人二",
			ContactPhone:   "13800000011",
			LoginPhone:     "13900000011",
			Password:       "Test123456",
		}
		_, err = service.Create(ctx, req2)
		assert.Error(t, err)
	})

	t.Run("创建企业-手机号已存在应失败", func(t *testing.T) {
		ctx := createEnterpriseTestContext(1)

		req1 := &dto.CreateEnterpriseReq{
			EnterpriseName: "企业三",
			EnterpriseCode: "ENT_PHONE_001",
			ContactName:    "联系人三",
			ContactPhone:   "13800000020",
			LoginPhone:     "13900000020",
			Password:       "Test123456",
		}
		_, err := service.Create(ctx, req1)
		require.NoError(t, err)

		req2 := &dto.CreateEnterpriseReq{
			EnterpriseName: "企业四",
			EnterpriseCode: "ENT_PHONE_002",
			ContactName:    "联系人四",
			ContactPhone:   "13800000021",
			LoginPhone:     "13900000020",
			Password:       "Test123456",
		}
		_, err = service.Create(ctx, req2)
		assert.Error(t, err)
	})

	t.Run("创建企业-未授权用户应失败", func(t *testing.T) {
		ctx := context.Background()

		req := &dto.CreateEnterpriseReq{
			EnterpriseName: "未授权企业",
			EnterpriseCode: "ENT_UNAUTH_001",
			ContactName:    "联系人",
			ContactPhone:   "13800000030",
			LoginPhone:     "13900000030",
			Password:       "Test123456",
		}

		_, err := service.Create(ctx, req)
		assert.Error(t, err)
	})
}

func TestEnterpriseService_Update(t *testing.T) {
	tx := testutils.NewTestTransaction(t)
	rdb := testutils.GetTestRedis(t)
	testutils.CleanTestRedisKeys(t, rdb)

	enterpriseStore := postgres.NewEnterpriseStore(tx, rdb)
	shopStore := postgres.NewShopStore(tx, rdb)
	accountStore := postgres.NewAccountStore(tx, rdb)

	service := enterprise.New(tx, enterpriseStore, shopStore, accountStore)

	t.Run("编辑企业", func(t *testing.T) {
		ctx := createEnterpriseTestContext(1)

		createReq := &dto.CreateEnterpriseReq{
			EnterpriseName: "待编辑企业",
			EnterpriseCode: "ENT_EDIT_001",
			ContactName:    "原联系人",
			ContactPhone:   "13800000040",
			LoginPhone:     "13900000040",
			Password:       "Test123456",
		}
		createResult, err := service.Create(ctx, createReq)
		require.NoError(t, err)

		newName := "编辑后企业"
		newContact := "新联系人"
		updateReq := &dto.UpdateEnterpriseRequest{
			EnterpriseName: &newName,
			ContactName:    &newContact,
		}

		updated, err := service.Update(ctx, createResult.Enterprise.ID, updateReq)
		require.NoError(t, err)
		assert.Equal(t, "编辑后企业", updated.EnterpriseName)
		assert.Equal(t, "新联系人", updated.ContactName)
	})

	t.Run("编辑不存在的企业应失败", func(t *testing.T) {
		ctx := createEnterpriseTestContext(1)

		newName := "不存在企业"
		updateReq := &dto.UpdateEnterpriseRequest{
			EnterpriseName: &newName,
		}

		_, err := service.Update(ctx, 99999, updateReq)
		assert.Error(t, err)
	})
}

func TestEnterpriseService_UpdateStatus(t *testing.T) {
	tx := testutils.NewTestTransaction(t)
	rdb := testutils.GetTestRedis(t)
	testutils.CleanTestRedisKeys(t, rdb)

	enterpriseStore := postgres.NewEnterpriseStore(tx, rdb)
	shopStore := postgres.NewShopStore(tx, rdb)
	accountStore := postgres.NewAccountStore(tx, rdb)

	service := enterprise.New(tx, enterpriseStore, shopStore, accountStore)

	t.Run("禁用企业-账号同步禁用", func(t *testing.T) {
		ctx := createEnterpriseTestContext(1)

		createReq := &dto.CreateEnterpriseReq{
			EnterpriseName: "待禁用企业",
			EnterpriseCode: "ENT_STATUS_001",
			ContactName:    "联系人",
			ContactPhone:   "13800000050",
			LoginPhone:     "13900000050",
			Password:       "Test123456",
		}
		createResult, err := service.Create(ctx, createReq)
		require.NoError(t, err)

		err = service.UpdateStatus(ctx, createResult.Enterprise.ID, constants.StatusDisabled)
		require.NoError(t, err)

		ent, err := service.GetByID(ctx, createResult.Enterprise.ID)
		require.NoError(t, err)
		assert.Equal(t, constants.StatusDisabled, ent.Status)

		var account model.Account
		err = tx.Where("enterprise_id = ?", createResult.Enterprise.ID).First(&account).Error
		require.NoError(t, err)
		assert.Equal(t, constants.StatusDisabled, account.Status)
	})

	t.Run("启用企业-账号同步启用", func(t *testing.T) {
		ctx := createEnterpriseTestContext(1)

		createReq := &dto.CreateEnterpriseReq{
			EnterpriseName: "待启用企业",
			EnterpriseCode: "ENT_STATUS_002",
			ContactName:    "联系人",
			ContactPhone:   "13800000051",
			LoginPhone:     "13900000051",
			Password:       "Test123456",
		}
		createResult, err := service.Create(ctx, createReq)
		require.NoError(t, err)

		err = service.UpdateStatus(ctx, createResult.Enterprise.ID, constants.StatusDisabled)
		require.NoError(t, err)

		err = service.UpdateStatus(ctx, createResult.Enterprise.ID, constants.StatusEnabled)
		require.NoError(t, err)

		ent, err := service.GetByID(ctx, createResult.Enterprise.ID)
		require.NoError(t, err)
		assert.Equal(t, constants.StatusEnabled, ent.Status)

		var account model.Account
		err = tx.Where("enterprise_id = ?", createResult.Enterprise.ID).First(&account).Error
		require.NoError(t, err)
		assert.Equal(t, constants.StatusEnabled, account.Status)
	})

	t.Run("更新不存在企业状态应失败", func(t *testing.T) {
		ctx := createEnterpriseTestContext(1)

		err := service.UpdateStatus(ctx, 99999, constants.StatusDisabled)
		assert.Error(t, err)
	})
}

func TestEnterpriseService_UpdatePassword(t *testing.T) {
	tx := testutils.NewTestTransaction(t)
	rdb := testutils.GetTestRedis(t)
	testutils.CleanTestRedisKeys(t, rdb)

	enterpriseStore := postgres.NewEnterpriseStore(tx, rdb)
	shopStore := postgres.NewShopStore(tx, rdb)
	accountStore := postgres.NewAccountStore(tx, rdb)

	service := enterprise.New(tx, enterpriseStore, shopStore, accountStore)

	t.Run("修改企业账号密码", func(t *testing.T) {
		ctx := createEnterpriseTestContext(1)

		createReq := &dto.CreateEnterpriseReq{
			EnterpriseName: "密码测试企业",
			EnterpriseCode: "ENT_PWD_001",
			ContactName:    "联系人",
			ContactPhone:   "13800000060",
			LoginPhone:     "13900000060",
			Password:       "OldPass123",
		}
		createResult, err := service.Create(ctx, createReq)
		require.NoError(t, err)

		err = service.UpdatePassword(ctx, createResult.Enterprise.ID, "NewPass456")
		require.NoError(t, err)

		var account model.Account
		err = tx.Where("enterprise_id = ?", createResult.Enterprise.ID).First(&account).Error
		require.NoError(t, err)
		assert.NotEqual(t, "OldPass123", account.Password)
		assert.NotEqual(t, "NewPass456", account.Password)
	})

	t.Run("修改不存在企业密码应失败", func(t *testing.T) {
		ctx := createEnterpriseTestContext(1)

		err := service.UpdatePassword(ctx, 99999, "NewPass789")
		assert.Error(t, err)
	})
}

func TestEnterpriseService_List(t *testing.T) {
	tx := testutils.NewTestTransaction(t)
	rdb := testutils.GetTestRedis(t)
	testutils.CleanTestRedisKeys(t, rdb)

	enterpriseStore := postgres.NewEnterpriseStore(tx, rdb)
	shopStore := postgres.NewShopStore(tx, rdb)
	accountStore := postgres.NewAccountStore(tx, rdb)

	service := enterprise.New(tx, enterpriseStore, shopStore, accountStore)

	t.Run("查询企业列表-空结果", func(t *testing.T) {
		ctx := createEnterpriseTestContext(1)

		req := &dto.EnterpriseListReq{
			Page:     1,
			PageSize: 20,
		}

		result, err := service.List(ctx, req)
		require.NoError(t, err)
		assert.NotNil(t, result)
		assert.GreaterOrEqual(t, result.Total, int64(0))
	})

	t.Run("查询企业列表-按名称筛选", func(t *testing.T) {
		ctx := createEnterpriseTestContext(1)

		ts := time.Now().UnixNano()
		searchKey := fmt.Sprintf("列表测试企业_%d", ts)
		for i := 0; i < 3; i++ {
			createReq := &dto.CreateEnterpriseReq{
				EnterpriseName: fmt.Sprintf("%s_%d", searchKey, i),
				EnterpriseCode: fmt.Sprintf("ENT_LIST_%d_%d", ts, i),
				ContactName:    "联系人",
				ContactPhone:   fmt.Sprintf("138%08d", ts%100000000+int64(i)),
				LoginPhone:     fmt.Sprintf("139%08d", ts%100000000+int64(i)),
				Password:       "Test123456",
			}
			_, err := service.Create(ctx, createReq)
			require.NoError(t, err)
		}

		req := &dto.EnterpriseListReq{
			Page:           1,
			PageSize:       20,
			EnterpriseName: searchKey,
		}

		result, err := service.List(ctx, req)
		require.NoError(t, err)
		assert.NotNil(t, result)
		assert.GreaterOrEqual(t, result.Total, int64(3))
	})

	t.Run("查询企业列表-按状态筛选", func(t *testing.T) {
		ctx := createEnterpriseTestContext(1)

		status := constants.StatusEnabled
		req := &dto.EnterpriseListReq{
			Page:     1,
			PageSize: 20,
			Status:   &status,
		}

		result, err := service.List(ctx, req)
		require.NoError(t, err)
		assert.NotNil(t, result)
	})
}
