// Package exchange 提供换货读取用例。
package exchange

import (
	"context"
	"time"

	"github.com/break/junhong_cmp_fiber/internal/model"
	"github.com/break/junhong_cmp_fiber/internal/model/dto"
	"github.com/break/junhong_cmp_fiber/internal/store/postgres"
	"github.com/break/junhong_cmp_fiber/pkg/constants"
	"github.com/break/junhong_cmp_fiber/pkg/errors"
	"github.com/break/junhong_cmp_fiber/pkg/middleware"
	"gorm.io/gorm"
)

// ListQuery 查询换货列表并完成权限、分页和响应投影。
type ListQuery struct {
	db *gorm.DB
}

type assetSide string

const (
	// oldAssetSide 表示旧资产查询侧。
	oldAssetSide assetSide = "old"
	// newAssetSide 表示新资产查询侧。
	newAssetSide assetSide = "new"
)

// NewListQuery 创建换货列表查询。
func NewListQuery(db *gorm.DB) *ListQuery {
	return &ListQuery{db: db}
}

// List 按新旧资产关键词和其他列表条件查询换货单。
func (q *ListQuery) List(ctx context.Context, req *dto.ExchangeListRequest) (*dto.ExchangeListResponse, error) {
	page := constants.DefaultPage
	if req.Page != nil {
		page = *req.Page
	}
	pageSize := constants.DefaultPageSize
	if req.PageSize != nil {
		pageSize = *req.PageSize
	}

	query := q.db.WithContext(ctx).Model(&model.ExchangeOrder{})
	query = middleware.ApplyShopFilter(ctx, query)
	query = applyListFilters(query, req)

	var total int64
	if err := query.Count(&total).Error; err != nil {
		return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询换货单数量失败")
	}

	var orders []*model.ExchangeOrder
	offset := (page - 1) * pageSize
	if err := query.Order("created_at DESC").Offset(offset).Limit(pageSize).Find(&orders).Error; err != nil {
		return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询换货单列表失败")
	}
	submitterIDs := make([]uint, 0, len(orders))
	for _, order := range orders {
		if order.Creator > 0 {
			submitterIDs = append(submitterIDs, order.Creator)
		}
	}
	accounts, err := postgres.NewAccountStore(q.db, nil).GetDisplayAccountsByIDs(ctx, submitterIDs)
	if err != nil {
		return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询换货提交人失败")
	}
	submitterNames := make(map[uint]string, len(accounts))
	for _, account := range accounts {
		submitterNames[account.ID] = account.Username
	}

	items := make([]*dto.ExchangeOrderResponse, 0, len(orders))
	for _, order := range orders {
		item := projectExchangeOrder(order)
		item.SubmitterName = submitterNames[order.Creator]
		items = append(items, item)
	}
	return &dto.ExchangeListResponse{List: items, Total: total, Page: page, PageSize: pageSize}, nil
}

// applyListFilters 组装列表计数和数据查询共用的全部过滤条件。
func applyListFilters(query *gorm.DB, req *dto.ExchangeListRequest) *gorm.DB {
	if req.Status != nil {
		query = query.Where("status = ?", *req.Status)
	}
	if req.FlowType != "" {
		query = query.Where("COALESCE(NULLIF(flow_type, ''), ?) = ?", constants.ExchangeFlowTypeShipping, req.FlowType)
	}
	query = applyAssetKeyword(query, oldAssetSide, req.OldAssetKeyword)
	query = applyAssetKeyword(query, newAssetSide, req.NewAssetKeyword)
	if req.CreatedAtStart != nil {
		query = query.Where("created_at >= ?", *req.CreatedAtStart)
	}
	if req.CreatedAtEnd != nil {
		query = query.Where("created_at <= ?", *req.CreatedAtEnd)
	}
	return query
}

// applyAssetKeyword 使用子查询按资产类型和主键命中，避免依赖历史快照内容或逐行读取资产。
func applyAssetKeyword(query *gorm.DB, side assetSide, keyword string) *gorm.DB {
	if keyword == "" {
		return query
	}
	like := "%" + keyword + "%"
	cardIDs := query.Session(&gorm.Session{NewDB: true}).Model(&model.IotCard{}).
		Select("id").
		Where("iccid LIKE ? OR msisdn LIKE ? OR virtual_no LIKE ?", like, like, like)
	deviceIDs := query.Session(&gorm.Session{NewDB: true}).Model(&model.Device{}).
		Select("id").
		Where("virtual_no LIKE ? OR imei LIKE ? OR sn LIKE ?", like, like, like)
	prefix := string(side)
	return query.Where(
		"("+prefix+"_asset_type = ? AND "+prefix+"_asset_id IN (?)) OR ("+prefix+"_asset_type = ? AND "+prefix+"_asset_id IN (?))",
		constants.ExchangeAssetTypeIotCard, cardIDs, constants.ExchangeAssetTypeDevice, deviceIDs,
	)
}

// projectExchangeOrder 将只读模型投影为列表响应，不用于后续写侧判断。
func projectExchangeOrder(order *model.ExchangeOrder) *dto.ExchangeOrderResponse {
	var deletedAt *time.Time
	if order.DeletedAt.Valid {
		deletedAt = &order.DeletedAt.Time
	}
	return &dto.ExchangeOrderResponse{
		ID: order.ID, ExchangeNo: order.ExchangeNo,
		FlowType: effectiveFlowType(order.FlowType), FlowTypeName: constants.GetExchangeFlowTypeName(order.FlowType),
		OldAssetType: order.OldAssetType, OldAssetID: order.OldAssetID, OldAssetIdentifier: order.OldAssetIdentifier,
		NewAssetType: order.NewAssetType, NewAssetID: order.NewAssetID, NewAssetIdentifier: order.NewAssetIdentifier,
		RecipientName: order.RecipientName, RecipientPhone: order.RecipientPhone, RecipientAddress: order.RecipientAddress,
		ExpressCompany: order.ExpressCompany, ExpressNo: order.ExpressNo,
		MigrateData: order.MigrateData, MigrationCompleted: order.MigrationCompleted, MigrationBalance: order.MigrationBalance,
		ShippedAt: order.ShippedAt, CompletedAt: order.CompletedAt,
		ExchangeReason: order.ExchangeReason, Remark: order.Remark,
		Status: order.Status, StatusName: constants.GetExchangeStatusName(order.Status), StatusText: constants.GetExchangeStatusName(order.Status),
		ShopID: order.ShopID, CreatedAt: order.CreatedAt, UpdatedAt: order.UpdatedAt, DeletedAt: deletedAt,
		SubmitterID: order.Creator, Creator: order.Creator, Updater: order.Updater,
	}
}

func effectiveFlowType(flowType string) string {
	if flowType == "" {
		return constants.ExchangeFlowTypeShipping
	}
	return flowType
}
