package postgres

import (
	"context"

	"gorm.io/gorm"

	"github.com/break/junhong_cmp_fiber/internal/model"
	"github.com/break/junhong_cmp_fiber/internal/store"
)

type PackageSeriesStore struct {
	db *gorm.DB
}

func NewPackageSeriesStore(db *gorm.DB) *PackageSeriesStore {
	return &PackageSeriesStore{db: db}
}

func (s *PackageSeriesStore) Create(ctx context.Context, series *model.PackageSeries) error {
	return s.db.WithContext(ctx).Create(series).Error
}

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

func (s *PackageSeriesStore) GetByCode(ctx context.Context, code string) (*model.PackageSeries, error) {
	var series model.PackageSeries
	if err := s.db.WithContext(ctx).Where("series_code = ?", code).First(&series).Error; err != nil {
		return nil, err
	}
	return &series, nil
}

// GetByIDs 批量查询套餐系列
func (s *PackageSeriesStore) GetByIDs(ctx context.Context, ids []uint) ([]*model.PackageSeries, error) {
	if len(ids) == 0 {
		return []*model.PackageSeries{}, nil
	}
	var seriesList []*model.PackageSeries
	if err := s.db.WithContext(ctx).Where("id IN ?", ids).Find(&seriesList).Error; err != nil {
		return nil, err
	}
	return seriesList, nil
}

func (s *PackageSeriesStore) Update(ctx context.Context, series *model.PackageSeries) error {
	return s.db.WithContext(ctx).Save(series).Error
}

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

func (s *PackageSeriesStore) List(ctx context.Context, opts *store.QueryOptions, filters map[string]interface{}) ([]*model.PackageSeries, int64, error) {
	var seriesList []*model.PackageSeries
	var total int64

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

	if seriesName, ok := filters["series_name"].(string); ok && seriesName != "" {
		query = query.Where("series_name LIKE ?", "%"+seriesName+"%")
	}
	if status, ok := filters["status"]; ok {
		query = query.Where("status = ?", status)
	}
	if enableOneTime, ok := filters["enable_one_time_commission"].(bool); ok {
		query = query.Where("enable_one_time_commission = ?", enableOneTime)
	}
	// 支持按系列 ID 列表过滤（用于代理用户只能看到分配给自己店铺的套餐系列）
	if seriesIDs, ok := filters["series_ids"].([]uint); ok && len(seriesIDs) > 0 {
		query = query.Where("id IN ?", seriesIDs)
	}

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

	if opts == nil {
		opts = store.DefaultQueryOptions()
	}
	offset := (opts.Page - 1) * opts.PageSize
	query = query.Offset(offset).Limit(opts.PageSize)

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

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

	return seriesList, total, nil
}

func (s *PackageSeriesStore) UpdateStatus(ctx context.Context, id uint, status int) error {
	return s.db.WithContext(ctx).Model(&model.PackageSeries{}).Where("id = ?", id).Update("status", status).Error
}

// GetByIDUnscoped 根据ID获取套餐系列（包括已删除的记录）
// 用于关联查询场景，确保已删除的系列信息仍能被展示
func (s *PackageSeriesStore) GetByIDUnscoped(ctx context.Context, id uint) (*model.PackageSeries, error) {
	var series model.PackageSeries
	if err := s.db.WithContext(ctx).Unscoped().First(&series, id).Error; err != nil {
		return nil, err
	}
	return &series, nil
}
