package unit

import (
	"context"
	"testing"

	"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/my_commission"
	"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 createMyCommissionTestContext(userID uint, shopID uint, userType int) context.Context {
	ctx := context.Background()
	ctx = context.WithValue(ctx, constants.ContextKeyUserID, userID)
	ctx = context.WithValue(ctx, constants.ContextKeyUserType, userType)
	ctx = context.WithValue(ctx, constants.ContextKeyShopID, shopID)
	return ctx
}

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

	shopStore := postgres.NewShopStore(tx, rdb)
	walletStore := postgres.NewWalletStore(tx, rdb)
	commissionWithdrawalRequestStore := postgres.NewCommissionWithdrawalRequestStore(tx, rdb)
	commissionWithdrawalSettingStore := postgres.NewCommissionWithdrawalSettingStore(tx, rdb)
	commissionRecordStore := postgres.NewCommissionRecordStore(tx, rdb)
	walletTransactionStore := postgres.NewWalletTransactionStore(tx, rdb)

	service := my_commission.New(
		tx, shopStore, walletStore,
		commissionWithdrawalRequestStore, commissionWithdrawalSettingStore,
		commissionRecordStore, walletTransactionStore,
	)

	t.Run("佣金概览-代理商用户成功", func(t *testing.T) {
		shop := &model.Shop{
			ShopName:     "概览测试店铺",
			ShopCode:     "MY_SHOP_001",
			Level:        1,
			ContactName:  "联系人",
			ContactPhone: "13800000001",
			Status:       constants.StatusEnabled,
		}
		shop.Creator = 1
		shop.Updater = 1
		err := tx.Create(shop).Error
		require.NoError(t, err)

		ctx := createMyCommissionTestContext(1, shop.ID, constants.UserTypeAgent)

		result, err := service.GetCommissionSummary(ctx)
		require.NoError(t, err)
		assert.NotNil(t, result)
		assert.Equal(t, shop.ID, result.ShopID)
		assert.Equal(t, "概览测试店铺", result.ShopName)
	})

	t.Run("佣金概览-非代理商用户应失败", func(t *testing.T) {
		ctx := createMyCommissionTestContext(1, 1, constants.UserTypePlatform)

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

	t.Run("佣金概览-店铺不存在应失败", func(t *testing.T) {
		ctx := createMyCommissionTestContext(1, 99999, constants.UserTypeAgent)

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

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

	shopStore := postgres.NewShopStore(tx, rdb)
	walletStore := postgres.NewWalletStore(tx, rdb)
	commissionWithdrawalRequestStore := postgres.NewCommissionWithdrawalRequestStore(tx, rdb)
	commissionWithdrawalSettingStore := postgres.NewCommissionWithdrawalSettingStore(tx, rdb)
	commissionRecordStore := postgres.NewCommissionRecordStore(tx, rdb)
	walletTransactionStore := postgres.NewWalletTransactionStore(tx, rdb)

	service := my_commission.New(
		tx, shopStore, walletStore,
		commissionWithdrawalRequestStore, commissionWithdrawalSettingStore,
		commissionRecordStore, walletTransactionStore,
	)

	t.Run("发起提现-无提现配置应失败", func(t *testing.T) {
		shop := &model.Shop{
			ShopName:     "提现测试店铺",
			ShopCode:     "MY_SHOP_002",
			Level:        1,
			ContactName:  "联系人",
			ContactPhone: "13800000002",
			Status:       constants.StatusEnabled,
		}
		shop.Creator = 1
		shop.Updater = 1
		err := tx.Create(shop).Error
		require.NoError(t, err)

		ctx := createMyCommissionTestContext(1, shop.ID, constants.UserTypeAgent)

		req := &dto.CreateMyWithdrawalReq{
			Amount:           10000,
			WithdrawalMethod: "alipay",
			AccountName:      "测试用户",
			AccountNumber:    "test@alipay.com",
		}

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

	t.Run("发起提现-金额低于最低限制应失败", func(t *testing.T) {
		shop := &model.Shop{
			ShopName:     "限额测试店铺",
			ShopCode:     "MY_SHOP_003",
			Level:        1,
			ContactName:  "联系人",
			ContactPhone: "13800000003",
			Status:       constants.StatusEnabled,
		}
		shop.Creator = 1
		shop.Updater = 1
		err := tx.Create(shop).Error
		require.NoError(t, err)

		setting := &model.CommissionWithdrawalSetting{
			DailyWithdrawalLimit: 5,
			MinWithdrawalAmount:  10000,
			FeeRate:              100,
			IsActive:             true,
		}
		setting.Creator = 1
		setting.Updater = 1
		err = tx.Create(setting).Error
		require.NoError(t, err)

		ctx := createMyCommissionTestContext(1, shop.ID, constants.UserTypeAgent)

		req := &dto.CreateMyWithdrawalReq{
			Amount:           5000,
			WithdrawalMethod: "alipay",
			AccountName:      "测试用户",
			AccountNumber:    "test@alipay.com",
		}

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

	t.Run("发起提现-余额不足应失败", func(t *testing.T) {
		shop := &model.Shop{
			ShopName:     "余额测试店铺",
			ShopCode:     "MY_SHOP_004",
			Level:        1,
			ContactName:  "联系人",
			ContactPhone: "13800000004",
			Status:       constants.StatusEnabled,
		}
		shop.Creator = 1
		shop.Updater = 1
		err := tx.Create(shop).Error
		require.NoError(t, err)

		wallet := &model.Wallet{
			ResourceType: constants.WalletResourceTypeShop,
			ResourceID:   shop.ID,
			WalletType:   constants.WalletTypeCommission,
			Balance:      5000,
		}
		err = tx.Create(wallet).Error
		require.NoError(t, err)

		ctx := createMyCommissionTestContext(1, shop.ID, constants.UserTypeAgent)

		req := &dto.CreateMyWithdrawalReq{
			Amount:           50000,
			WithdrawalMethod: "alipay",
			AccountName:      "测试用户",
			AccountNumber:    "test@alipay.com",
		}

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

	t.Run("发起提现-非代理商用户应失败", func(t *testing.T) {
		ctx := createMyCommissionTestContext(1, 1, constants.UserTypePlatform)

		req := &dto.CreateMyWithdrawalReq{
			Amount:           10000,
			WithdrawalMethod: "alipay",
			AccountName:      "测试用户",
			AccountNumber:    "test@alipay.com",
		}

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

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

	shopStore := postgres.NewShopStore(tx, rdb)
	walletStore := postgres.NewWalletStore(tx, rdb)
	commissionWithdrawalRequestStore := postgres.NewCommissionWithdrawalRequestStore(tx, rdb)
	commissionWithdrawalSettingStore := postgres.NewCommissionWithdrawalSettingStore(tx, rdb)
	commissionRecordStore := postgres.NewCommissionRecordStore(tx, rdb)
	walletTransactionStore := postgres.NewWalletTransactionStore(tx, rdb)

	service := my_commission.New(
		tx, shopStore, walletStore,
		commissionWithdrawalRequestStore, commissionWithdrawalSettingStore,
		commissionRecordStore, walletTransactionStore,
	)

	t.Run("查询提现记录-空结果", func(t *testing.T) {
		shop := &model.Shop{
			ShopName:     "提现记录测试店铺",
			ShopCode:     "MY_SHOP_005",
			Level:        1,
			ContactName:  "联系人",
			ContactPhone: "13800000005",
			Status:       constants.StatusEnabled,
		}
		shop.Creator = 1
		shop.Updater = 1
		err := tx.Create(shop).Error
		require.NoError(t, err)

		ctx := createMyCommissionTestContext(1, shop.ID, constants.UserTypeAgent)

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

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

	t.Run("查询提现记录-按状态筛选", func(t *testing.T) {
		shop := &model.Shop{
			ShopName:     "状态筛选测试店铺",
			ShopCode:     "MY_SHOP_006",
			Level:        1,
			ContactName:  "联系人",
			ContactPhone: "13800000006",
			Status:       constants.StatusEnabled,
		}
		shop.Creator = 1
		shop.Updater = 1
		err := tx.Create(shop).Error
		require.NoError(t, err)

		ctx := createMyCommissionTestContext(1, shop.ID, constants.UserTypeAgent)

		status := 1
		req := &dto.MyWithdrawalListReq{
			Page:     1,
			PageSize: 20,
			Status:   &status,
		}

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

	t.Run("查询提现记录-非代理商用户应失败", func(t *testing.T) {
		ctx := createMyCommissionTestContext(1, 1, constants.UserTypePlatform)

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

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

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

	shopStore := postgres.NewShopStore(tx, rdb)
	walletStore := postgres.NewWalletStore(tx, rdb)
	commissionWithdrawalRequestStore := postgres.NewCommissionWithdrawalRequestStore(tx, rdb)
	commissionWithdrawalSettingStore := postgres.NewCommissionWithdrawalSettingStore(tx, rdb)
	commissionRecordStore := postgres.NewCommissionRecordStore(tx, rdb)
	walletTransactionStore := postgres.NewWalletTransactionStore(tx, rdb)

	service := my_commission.New(
		tx, shopStore, walletStore,
		commissionWithdrawalRequestStore, commissionWithdrawalSettingStore,
		commissionRecordStore, walletTransactionStore,
	)

	t.Run("查询佣金明细-空结果", func(t *testing.T) {
		shop := &model.Shop{
			ShopName:     "佣金明细测试店铺",
			ShopCode:     "MY_SHOP_007",
			Level:        1,
			ContactName:  "联系人",
			ContactPhone: "13800000007",
			Status:       constants.StatusEnabled,
		}
		shop.Creator = 1
		shop.Updater = 1
		err := tx.Create(shop).Error
		require.NoError(t, err)

		ctx := createMyCommissionTestContext(1, shop.ID, constants.UserTypeAgent)

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

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

	t.Run("查询佣金明细-按类型筛选", func(t *testing.T) {
		shop := &model.Shop{
			ShopName:     "类型筛选测试店铺",
			ShopCode:     "MY_SHOP_008",
			Level:        1,
			ContactName:  "联系人",
			ContactPhone: "13800000008",
			Status:       constants.StatusEnabled,
		}
		shop.Creator = 1
		shop.Updater = 1
		err := tx.Create(shop).Error
		require.NoError(t, err)

		ctx := createMyCommissionTestContext(1, shop.ID, constants.UserTypeAgent)

		commissionSource := "one_time"
		req := &dto.MyCommissionRecordListReq{
			Page:             1,
			PageSize:         20,
			CommissionSource: &commissionSource,
		}

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

	t.Run("查询佣金明细-非代理商用户应失败", func(t *testing.T) {
		ctx := createMyCommissionTestContext(1, 1, constants.UserTypePlatform)

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

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