package postgres

import (
	"context"

	"gorm.io/gorm"

	"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/break/junhong_cmp_fiber/pkg/middleware"
)

type PackageStore struct {
	db *gorm.DB
}

func NewPackageStore(db *gorm.DB) *PackageStore {
	return &PackageStore{db: db}
}

func (s *PackageStore) Create(ctx context.Context, pkg *model.Package) error {
	return s.db.WithContext(ctx).Create(pkg).Error
}

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

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

func (s *PackageStore) Update(ctx context.Context, pkg *model.Package) error {
	return s.db.WithContext(ctx).Save(pkg).Error
}

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

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

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

	// 代理用户额外过滤：只能看到已分配的套餐
	userType := middleware.GetUserTypeFromContext(ctx)
	shopID := middleware.GetShopIDFromContext(ctx)
	if userType == constants.UserTypeAgent && shopID > 0 {
		query = query.Joins("INNER JOIN tb_shop_package_allocation ON tb_shop_package_allocation.package_id = tb_package.id").
			Where("tb_shop_package_allocation.shop_id = ? AND tb_shop_package_allocation.status = ?",
				shopID, constants.StatusEnabled)
	}

	if packageName, ok := filters["package_name"].(string); ok && packageName != "" {
		query = query.Where("tb_package.package_name LIKE ?", "%"+packageName+"%")
	}
	if seriesID, ok := filters["series_id"].(uint); ok && seriesID > 0 {
		query = query.Where("tb_package.series_id = ?", seriesID)
	}
	if status, ok := filters["status"]; ok {
		query = query.Where("tb_package.status = ?", status)
	}
	if shelfStatus, ok := filters["shelf_status"]; ok {
		query = query.Where("tb_package.shelf_status = ?", shelfStatus)
	}
	if packageType, ok := filters["package_type"].(string); ok && packageType != "" {
		query = query.Where("tb_package.package_type = ?", packageType)
	}

	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(&packages).Error; err != nil {
		return nil, 0, err
	}

	return packages, total, nil
}

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

func (s *PackageStore) UpdateShelfStatus(ctx context.Context, id uint, shelfStatus int) error {
	return s.db.WithContext(ctx).Model(&model.Package{}).Where("id = ?", id).Update("shelf_status", shelfStatus).Error
}
