package postgres

import (
	"context"
	"testing"

	"github.com/break/junhong_cmp_fiber/internal/model"
	"github.com/break/junhong_cmp_fiber/tests/testutils"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"gorm.io/gorm"
)

func TestShopSeriesAllocationStore_GetByShopAndSeries(t *testing.T) {
	tx := testutils.NewTestTransaction(t)
	ctx := context.Background()

	s := NewShopSeriesAllocationStore(tx)

	// 创建测试数据
	allocation := &model.ShopSeriesAllocation{
		ShopID:          1,
		SeriesID:        100,
		AllocatorShopID: 0,
		Status:          1,
	}
	require.NoError(t, s.Create(ctx, allocation))

	t.Run("查询存在的分配", func(t *testing.T) {
		result, err := s.GetByShopAndSeries(ctx, 1, 100)
		require.NoError(t, err)
		assert.NotNil(t, result)
		assert.Equal(t, uint(1), result.ShopID)
		assert.Equal(t, uint(100), result.SeriesID)
	})

	t.Run("查询不存在的分配", func(t *testing.T) {
		result, err := s.GetByShopAndSeries(ctx, 999, 999)
		assert.Error(t, err)
		assert.Equal(t, gorm.ErrRecordNotFound, err)
		assert.Nil(t, result)
	})
}

func TestShopSeriesAllocationStore_Create(t *testing.T) {
	tx := testutils.NewTestTransaction(t)
	ctx := context.Background()

	s := NewShopSeriesAllocationStore(tx)

	allocation := &model.ShopSeriesAllocation{
		ShopID:          1,
		SeriesID:        100,
		AllocatorShopID: 0,
		Status:          1,
	}

	err := s.Create(ctx, allocation)
	require.NoError(t, err)
	assert.NotZero(t, allocation.ID)
}

func TestShopSeriesAllocationStore_GetByID(t *testing.T) {
	tx := testutils.NewTestTransaction(t)
	ctx := context.Background()

	s := NewShopSeriesAllocationStore(tx)

	allocation := &model.ShopSeriesAllocation{
		ShopID:          1,
		SeriesID:        100,
		AllocatorShopID: 0,
		Status:          1,
	}
	require.NoError(t, s.Create(ctx, allocation))

	result, err := s.GetByID(ctx, allocation.ID)
	require.NoError(t, err)
	assert.NotNil(t, result)
	assert.Equal(t, allocation.ID, result.ID)
}

func TestShopSeriesAllocationStore_List(t *testing.T) {
	tx := testutils.NewTestTransaction(t)
	ctx := context.Background()

	s := NewShopSeriesAllocationStore(tx)

	// 创建测试数据
	allocations := []*model.ShopSeriesAllocation{
		{ShopID: 1, SeriesID: 100, AllocatorShopID: 0, Status: 1},
		{ShopID: 1, SeriesID: 101, AllocatorShopID: 0, Status: 1},
		{ShopID: 2, SeriesID: 100, AllocatorShopID: 0, Status: 1},
	}
	for _, a := range allocations {
		require.NoError(t, s.Create(ctx, a))
	}

	t.Run("按店铺ID过滤", func(t *testing.T) {
		filters := map[string]interface{}{"shop_id": uint(1)}
		result, total, err := s.List(ctx, nil, filters)
		require.NoError(t, err)
		assert.Equal(t, int64(2), total)
		assert.Len(t, result, 2)
	})

	t.Run("按系列ID过滤", func(t *testing.T) {
		filters := map[string]interface{}{"series_id": uint(100)}
		result, total, err := s.List(ctx, nil, filters)
		require.NoError(t, err)
		assert.Equal(t, int64(2), total)
		assert.Len(t, result, 2)
	})
}
