package dao

import (
	"errors"
	"fmt"
	"opencatd-open/internal/model"
	"time"

	"gorm.io/gorm"
)

// 确保 UserDAO 实现了 UserRepository 接口
var _ UserRepository = (*UserDAO)(nil)

// UserRepository 定义用户数据访问操作的接口
type UserRepository interface {
	Create(user *model.User) error
	GetByID(id int64) (*model.User, error)
	GetByUsername(username string) (*model.User, error)
	Update(user *model.User) error
	Delete(id int64) error
	List(limit, offset int, condition map[string]interface{}) ([]model.User, int64, error)
	// Enable(id int64) error
	// Disable(id int64) error
	BatchEnable(ids []int64, condition []string) error
	BatchDisable(ids []int64, condition []string) error
	BatchDelete(ids []int64, condition []string) error
}

type UserDAO struct {
	db *gorm.DB
}

func NewUserDAO(db *gorm.DB) *UserDAO {
	return &UserDAO{db: db}
}

// 创建用户
func (dao *UserDAO) Create(user *model.User) error {
	if user == nil {
		return errors.New("user is nil")
	}
	fmt.Println(*user)

	return dao.db.Transaction(func(tx *gorm.DB) error {
		// 创建用户
		if err := tx.Create(user).Error; err != nil {
			return fmt.Errorf("failed to create user: %w", err)
		}

		return nil
	})
}

// 根据ID获取用户
func (dao *UserDAO) GetByID(id int64) (*model.User, error) {
	var user model.User
	// err := dao.db.First(&user, id).Error
	err := dao.db.Preload("Tokens", "user_id = ?", id).First(&user, id).Error
	if err != nil {
		return nil, err
	}
	return &user, nil
}

// 根据用户名获取用户
func (dao *UserDAO) GetByUsername(username string) (*model.User, error) {
	var user model.User
	// err := dao.db.Where("user_name = ?", username).First(&user).Error
	err := dao.db.Preload("Tokens").Where("user_name = ?", username).First(&user).Error
	if err != nil {
		return nil, err
	}
	return &user, nil
}

// 更新用户信息
func (dao *UserDAO) Update(user *model.User) error {
	if user == nil {
		return errors.New("user is nil")
	}

	user.UpdatedAt = time.Now().Unix()
	return dao.db.Save(user).Error
}

// 删除用户
func (dao *UserDAO) Delete(id int64) error {
	return dao.db.Unscoped().Delete(&model.User{}, id).Error
	// return dao.db.Model(&model.User{}).Where("id = ?", id).Update("status", 2).Error
}

// 获取用户列表
func (dao *UserDAO) List(limit, offset int, condition map[string]interface{}) ([]model.User, int64, error) {
	if offset < 0 {
		offset = 0
	}
	var users []model.User
	var total int64

	query := dao.db.Preload("Tokens").Model(&model.User{})

	for k, v := range condition {
		query = query.Where(k, v)
	}
	err := query.Limit(limit).Offset(offset).Find(&users).Error
	if err != nil {
		return nil, 0, err
	}
	query = dao.db.Model(&model.User{})
	for k, v := range condition {
		query = query.Where(k, v)
	}
	query.Count(&total)

	return users, total, nil
}

// 启用User
func (dao *UserDAO) Enable(id uint) error {
	return dao.db.Model(&model.User{}).Where("id = ?", id).Update("active", true).Error
}

// 禁用User
func (dao *UserDAO) Disable(id uint) error {
	return dao.db.Model(&model.User{}).Where("id = ?", id).Update("active", false).Error
}

// 批量启用User
func (dao *UserDAO) BatchEnable(ids []int64, condition []string) error {
	if len(ids) == 0 {
		return errors.New("ids is empty")
	}
	query := dao.db.Model(&model.User{}).Where("id IN ?", ids)
	for _, value := range condition {
		query = query.Where(value)
	}
	return query.Update("active", true).Error
}

// 批量禁用User
func (dao *UserDAO) BatchDisable(ids []int64, condition []string) error {
	if len(ids) == 0 {
		return errors.New("ids is empty")
	}
	query := dao.db.Model(&model.User{}).Where("id IN ?", ids)
	for _, value := range condition {
		query = query.Where(value)
	}
	return query.Update("active", false).Error
}

// 批量删除用户
func (dao *UserDAO) BatchDelete(ids []int64, condition []string) error {
	if len(ids) == 0 {
		return errors.New("ids is empty")
	}
	query := dao.db.Unscoped().Where("id IN ?", ids)
	for _, value := range condition {
		query = query.Where(value)
	}
	return query.Delete(&model.User{}).Error
}
