package postgres

import (
	"context"

	"github.com/break/junhong_cmp_fiber/internal/model"
	"github.com/break/junhong_cmp_fiber/internal/store"
	"github.com/break/junhong_cmp_fiber/pkg/constants"
	"github.com/redis/go-redis/v9"
	"gorm.io/gorm"
)

type IotCardStore struct {
	db    *gorm.DB
	redis *redis.Client
}

func NewIotCardStore(db *gorm.DB, redis *redis.Client) *IotCardStore {
	return &IotCardStore{
		db:    db,
		redis: redis,
	}
}

func (s *IotCardStore) Create(ctx context.Context, card *model.IotCard) error {
	return s.db.WithContext(ctx).Create(card).Error
}

func (s *IotCardStore) CreateBatch(ctx context.Context, cards []*model.IotCard) error {
	if len(cards) == 0 {
		return nil
	}
	return s.db.WithContext(ctx).CreateInBatches(cards, 100).Error
}

func (s *IotCardStore) GetByID(ctx context.Context, id uint) (*model.IotCard, error) {
	var card model.IotCard
	if err := s.db.WithContext(ctx).First(&card, id).Error; err != nil {
		return nil, err
	}
	return &card, nil
}

func (s *IotCardStore) GetByICCID(ctx context.Context, iccid string) (*model.IotCard, error) {
	var card model.IotCard
	if err := s.db.WithContext(ctx).Where("iccid = ?", iccid).First(&card).Error; err != nil {
		return nil, err
	}
	return &card, nil
}

func (s *IotCardStore) GetByIDs(ctx context.Context, ids []uint) ([]*model.IotCard, error) {
	if len(ids) == 0 {
		return []*model.IotCard{}, nil
	}
	var cards []*model.IotCard
	if err := s.db.WithContext(ctx).Where("id IN ?", ids).Find(&cards).Error; err != nil {
		return nil, err
	}
	return cards, nil
}

func (s *IotCardStore) ExistsByICCID(ctx context.Context, iccid string) (bool, error) {
	var count int64
	if err := s.db.WithContext(ctx).Model(&model.IotCard{}).Where("iccid = ?", iccid).Count(&count).Error; err != nil {
		return false, err
	}
	return count > 0, nil
}

func (s *IotCardStore) ExistsByICCIDBatch(ctx context.Context, iccids []string) (map[string]bool, error) {
	if len(iccids) == 0 {
		return make(map[string]bool), nil
	}

	var existingICCIDs []string
	if err := s.db.WithContext(ctx).Model(&model.IotCard{}).
		Where("iccid IN ?", iccids).
		Pluck("iccid", &existingICCIDs).Error; err != nil {
		return nil, err
	}

	result := make(map[string]bool)
	for _, iccid := range existingICCIDs {
		result[iccid] = true
	}
	return result, nil
}

func (s *IotCardStore) Update(ctx context.Context, card *model.IotCard) error {
	return s.db.WithContext(ctx).Save(card).Error
}

func (s *IotCardStore) Delete(ctx context.Context, id uint) error {
	return s.db.WithContext(ctx).Delete(&model.IotCard{}, id).Error
}

func (s *IotCardStore) List(ctx context.Context, opts *store.QueryOptions, filters map[string]any) ([]*model.IotCard, int64, error) {
	var cards []*model.IotCard
	var total int64

	query := s.db.WithContext(ctx).Model(&model.IotCard{})

	// 企业用户特殊处理：只能看到授权给自己的卡
	if enterpriseID, ok := filters["authorized_enterprise_id"].(uint); ok && enterpriseID > 0 {
		query = query.Where("id IN (?)",
			s.db.Table("tb_enterprise_card_authorization").
				Select("card_id").
				Where("enterprise_id = ? AND revoked_at IS NULL AND deleted_at IS NULL", enterpriseID))
	}

	// 基础过滤条件
	if status, ok := filters["status"].(int); ok && status > 0 {
		query = query.Where("status = ?", status)
	}
	if carrierID, ok := filters["carrier_id"].(uint); ok && carrierID > 0 {
		query = query.Where("carrier_id = ?", carrierID)
	}
	if shopID, ok := filters["shop_id"].(uint); ok && shopID > 0 {
		query = query.Where("shop_id = ?", shopID)
	}
	if iccid, ok := filters["iccid"].(string); ok && iccid != "" {
		query = query.Where("iccid LIKE ?", "%"+iccid+"%")
	}
	if msisdn, ok := filters["msisdn"].(string); ok && msisdn != "" {
		query = query.Where("msisdn LIKE ?", "%"+msisdn+"%")
	}
	if batchNo, ok := filters["batch_no"].(string); ok && batchNo != "" {
		query = query.Where("batch_no = ?", batchNo)
	}
	if packageID, ok := filters["package_id"].(uint); ok && packageID > 0 {
		query = query.Where("id IN (?)",
			s.db.Table("tb_package_usage").
				Select("iot_card_id").
				Where("package_id = ? AND deleted_at IS NULL", packageID))
	}
	if isDistributed, ok := filters["is_distributed"].(bool); ok {
		if isDistributed {
			query = query.Where("shop_id IS NOT NULL")
		} else {
			query = query.Where("shop_id IS NULL")
		}
	}
	if iccidStart, ok := filters["iccid_start"].(string); ok && iccidStart != "" {
		query = query.Where("iccid >= ?", iccidStart)
	}
	if iccidEnd, ok := filters["iccid_end"].(string); ok && iccidEnd != "" {
		query = query.Where("iccid <= ?", iccidEnd)
	}
	if seriesID, ok := filters["series_id"].(uint); ok && seriesID > 0 {
		query = query.Where("series_id = ?", seriesID)
	}

	// 统计总数
	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// 分页处理
	if opts == nil {
		opts = &store.QueryOptions{
			Page:     1,
			PageSize: constants.DefaultPageSize,
		}
	}
	offset := (opts.Page - 1) * opts.PageSize
	query = query.Offset(offset).Limit(opts.PageSize)

	// 排序
	if opts.OrderBy != "" {
		query = query.Order(opts.OrderBy)
	} else {
		query = query.Order("created_at DESC")
	}

	// 查询结果
	if err := query.Find(&cards).Error; err != nil {
		return nil, 0, err
	}

	return cards, total, nil
}

func (s *IotCardStore) ListStandalone(ctx context.Context, opts *store.QueryOptions, filters map[string]any) ([]*model.IotCard, int64, error) {
	var cards []*model.IotCard
	var total int64

	query := s.db.WithContext(ctx).Model(&model.IotCard{})

	query = query.Where("id NOT IN (?)",
		s.db.Model(&model.DeviceSimBinding{}).
			Select("iot_card_id").
			Where("bind_status = ?", 1))

	if status, ok := filters["status"].(int); ok && status > 0 {
		query = query.Where("status = ?", status)
	}
	if carrierID, ok := filters["carrier_id"].(uint); ok && carrierID > 0 {
		query = query.Where("carrier_id = ?", carrierID)
	}
	if shopID, ok := filters["shop_id"].(uint); ok && shopID > 0 {
		query = query.Where("shop_id = ?", shopID)
	}
	if iccid, ok := filters["iccid"].(string); ok && iccid != "" {
		query = query.Where("iccid LIKE ?", "%"+iccid+"%")
	}
	if msisdn, ok := filters["msisdn"].(string); ok && msisdn != "" {
		query = query.Where("msisdn LIKE ?", "%"+msisdn+"%")
	}
	if batchNo, ok := filters["batch_no"].(string); ok && batchNo != "" {
		query = query.Where("batch_no = ?", batchNo)
	}
	if packageID, ok := filters["package_id"].(uint); ok && packageID > 0 {
		query = query.Where("id IN (?)",
			s.db.Table("tb_package_usage").
				Select("iot_card_id").
				Where("package_id = ? AND deleted_at IS NULL", packageID))
	}
	if isDistributed, ok := filters["is_distributed"].(bool); ok {
		if isDistributed {
			query = query.Where("shop_id IS NOT NULL")
		} else {
			query = query.Where("shop_id IS NULL")
		}
	}
	if iccidStart, ok := filters["iccid_start"].(string); ok && iccidStart != "" {
		query = query.Where("iccid >= ?", iccidStart)
	}
	if iccidEnd, ok := filters["iccid_end"].(string); ok && iccidEnd != "" {
		query = query.Where("iccid <= ?", iccidEnd)
	}
	if isReplaced, ok := filters["is_replaced"].(bool); ok {
		if isReplaced {
			query = query.Where("id IN (?)",
				s.db.Table("tb_card_replacement_record").
					Select("old_iot_card_id").
					Where("deleted_at IS NULL"))
		} else {
			query = query.Where("id NOT IN (?)",
				s.db.Table("tb_card_replacement_record").
					Select("old_iot_card_id").
					Where("deleted_at IS NULL"))
		}
	}
	if seriesID, ok := filters["series_id"].(uint); ok && seriesID > 0 {
		query = query.Where("series_id = ?", seriesID)
	}

	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	if opts == nil {
		opts = &store.QueryOptions{
			Page:     1,
			PageSize: constants.DefaultPageSize,
		}
	}
	offset := (opts.Page - 1) * opts.PageSize
	query = query.Offset(offset).Limit(opts.PageSize)

	if opts.OrderBy != "" {
		query = query.Order(opts.OrderBy)
	} else {
		query = query.Order("created_at DESC")
	}

	if err := query.Find(&cards).Error; err != nil {
		return nil, 0, err
	}

	return cards, total, nil
}

func (s *IotCardStore) GetByICCIDs(ctx context.Context, iccids []string) ([]*model.IotCard, error) {
	if len(iccids) == 0 {
		return nil, nil
	}
	var cards []*model.IotCard
	if err := s.db.WithContext(ctx).Where("iccid IN ?", iccids).Find(&cards).Error; err != nil {
		return nil, err
	}
	return cards, nil
}

func (s *IotCardStore) GetStandaloneByICCIDRange(ctx context.Context, iccidStart, iccidEnd string, shopID *uint) ([]*model.IotCard, error) {
	query := s.db.WithContext(ctx).Model(&model.IotCard{}).
		Where("id NOT IN (?)",
			s.db.Model(&model.DeviceSimBinding{}).
				Select("iot_card_id").
				Where("bind_status = ?", 1)).
		Where("iccid >= ? AND iccid <= ?", iccidStart, iccidEnd)

	if shopID == nil {
		query = query.Where("shop_id IS NULL")
	} else {
		query = query.Where("shop_id = ?", *shopID)
	}

	var cards []*model.IotCard
	if err := query.Find(&cards).Error; err != nil {
		return nil, err
	}
	return cards, nil
}

func (s *IotCardStore) GetStandaloneByFilters(ctx context.Context, filters map[string]any, shopID *uint) ([]*model.IotCard, error) {
	query := s.db.WithContext(ctx).Model(&model.IotCard{}).
		Where("id NOT IN (?)",
			s.db.Model(&model.DeviceSimBinding{}).
				Select("iot_card_id").
				Where("bind_status = ?", 1))

	if shopID == nil {
		query = query.Where("shop_id IS NULL")
	} else {
		query = query.Where("shop_id = ?", *shopID)
	}

	if status, ok := filters["status"].(int); ok && status > 0 {
		query = query.Where("status = ?", status)
	}
	if carrierID, ok := filters["carrier_id"].(uint); ok && carrierID > 0 {
		query = query.Where("carrier_id = ?", carrierID)
	}
	if batchNo, ok := filters["batch_no"].(string); ok && batchNo != "" {
		query = query.Where("batch_no = ?", batchNo)
	}

	var cards []*model.IotCard
	if err := query.Find(&cards).Error; err != nil {
		return nil, err
	}
	return cards, nil
}

func (s *IotCardStore) BatchUpdateShopIDAndStatus(ctx context.Context, cardIDs []uint, shopID *uint, status int) error {
	if len(cardIDs) == 0 {
		return nil
	}
	updates := map[string]any{
		"shop_id": shopID,
		"status":  status,
	}
	return s.db.WithContext(ctx).Model(&model.IotCard{}).
		Where("id IN ?", cardIDs).
		Updates(updates).Error
}

func (s *IotCardStore) GetBoundCardIDs(ctx context.Context, cardIDs []uint) ([]uint, error) {
	if len(cardIDs) == 0 {
		return nil, nil
	}
	var boundIDs []uint
	err := s.db.WithContext(ctx).Model(&model.DeviceSimBinding{}).
		Where("iot_card_id IN ? AND bind_status = ?", cardIDs, 1).
		Pluck("iot_card_id", &boundIDs).Error
	return boundIDs, err
}

func (s *IotCardStore) GetByIDsWithEnterpriseFilter(ctx context.Context, cardIDs []uint, enterpriseID *uint) ([]*model.IotCard, error) {
	if len(cardIDs) == 0 {
		return []*model.IotCard{}, nil
	}
	query := s.db.WithContext(ctx).Model(&model.IotCard{})

	if enterpriseID != nil && *enterpriseID > 0 {
		query = query.Where("id IN (?) AND id IN (?)",
			cardIDs,
			s.db.Table("tb_enterprise_card_authorization").
				Select("card_id").
				Where("enterprise_id = ? AND revoked_at IS NULL AND deleted_at IS NULL", *enterpriseID))
	} else {
		query = query.Where("id IN ?", cardIDs)
	}

	var cards []*model.IotCard
	if err := query.Find(&cards).Error; err != nil {
		return nil, err
	}
	return cards, nil
}

// BatchUpdateSeriesID 批量更新卡的套餐系列ID
// 用于批量设置或清除卡与套餐系列的关联关系
func (s *IotCardStore) BatchUpdateSeriesID(ctx context.Context, cardIDs []uint, seriesID *uint) error {
	if len(cardIDs) == 0 {
		return nil
	}
	return s.db.WithContext(ctx).Model(&model.IotCard{}).
		Where("id IN ?", cardIDs).
		Update("series_id", seriesID).Error
}

// ListBySeriesID 根据套餐系列ID查询卡列表
// 用于查询某个套餐系列下的所有卡
func (s *IotCardStore) ListBySeriesID(ctx context.Context, seriesID uint) ([]*model.IotCard, error) {
	var cards []*model.IotCard
	if err := s.db.WithContext(ctx).Where("series_id = ?", seriesID).Find(&cards).Error; err != nil {
		return nil, err
	}
	return cards, nil
}
