package repositories

import (
	"log"
	"time"

	"github.com/niangaodev/art-code/config"
	"github.com/niangaodev/art-code/models"
	"gorm.io/gorm"
)

// GetRoles 获取所有角色
func GetRoles() ([]models.Role, error) {
	var roles []models.Role
	err := config.DB.Model(&models.Role{}).
		Preload("Permissions").
		Where("deleted_at = ?", 0).
		Find(&roles).Error
	if err != nil {
		log.Printf("Error getting roles: %v", err)
		return nil, err
	}
	return roles, nil
}

// GetRoleByID 根据ID获取角色
func GetRoleByID(id uint) (*models.Role, error) {
	var role models.Role
	err := config.DB.Model(&models.Role{}).
		Preload("Permissions").
		Where("id = ? AND deleted_at = ?", id, 0).
		First(&role).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		}
		log.Printf("Error getting role by ID: %v", err)
		return nil, err
	}
	return &role, nil
}

// GetRoleByName 根据名称获取角色
func GetRoleByName(name string) (*models.Role, error) {
	var role models.Role
	err := config.DB.Model(&models.Role{}).
		Where("name = ? AND deleted_at = ?", name, 0).
		First(&role).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		}
		log.Printf("Error getting role by name: %v", err)
		return nil, err
	}
	return &role, nil
}

// CreateRole 创建角色
func CreateRole(role *models.Role) error {
	err := config.DB.Create(role).Error
	if err != nil {
		log.Printf("Error creating role: %v", err)
		return err
	}
	return nil
}

// UpdateRole 更新角色
func UpdateRole(role *models.Role) error {
	err := config.DB.Model(&models.Role{}).
		Where("id = ? AND deleted_at = ?", role.ID, 0).
		Updates(map[string]interface{}{
			"name":        role.Name,
			"description": role.Description,
			"updated_at":  time.Now().Unix(),
		}).Error
	if err != nil {
		log.Printf("Error updating role: %v", err)
		return err
	}
	return nil
}

// DeleteRole 删除角色 (Soft Delete)
func DeleteRole(id uint) error {
	err := config.DB.Model(&models.Role{}).
		Where("id = ?", id).
		Update("deleted_at", time.Now().Unix()).Error
	if err != nil {
		log.Printf("Error deleting role: %v", err)
		return err
	}
	return nil
}

// AssignPermissionsToRole 给角色分配权限
func AssignPermissionsToRole(roleID uint, permissionIDs []uint) error {
	return config.DB.Transaction(func(tx *gorm.DB) error {
		// 先删除旧权限
		err := tx.Exec("DELETE FROM role_permissions WHERE role_id = ?", roleID).Error
		if err != nil {
			return err
		}

		// 插入新权限
		if len(permissionIDs) > 0 {
			for _, permID := range permissionIDs {
				err = tx.Exec("INSERT INTO role_permissions (role_id, permission_id) VALUES (?, ?)", roleID, permID).Error
				if err != nil {
					return err
				}
			}
		}

		return nil
	})
}

// BuildRoleResponse 构建角色响应
func BuildRoleResponse(role *models.Role) *models.RoleResponse {
	return &models.RoleResponse{
		ID:          role.ID,
		Name:        role.Name,
		Description: role.Description,
		Permissions: BuildPermissionsResponse(role.Permissions),
		CreatedAt:   time.Unix(role.CreatedAt, 0).Format("2006-01-02 15:04:05"),
		UpdatedAt:   time.Unix(role.UpdatedAt, 0).Format("2006-01-02 15:04:05"),
	}
}

// BuildRolesResponse 构建角色列表响应
func BuildRolesResponse(roles []models.Role) []models.RoleResponse {
	var responses []models.RoleResponse
	for _, role := range roles {
		responses = append(responses, *BuildRoleResponse(&role))
	}
	return responses
}
