package repositories

import (
	"log"
	"time"

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

// GetPermissions 获取所有权限
func GetPermissions() ([]models.Permission, error) {
	var permissions []models.Permission
	err := config.DB.Model(&models.Permission{}).
		Where("deleted_at = ?", 0).
		Find(&permissions).Error
	if err != nil {
		log.Printf("Error getting permissions: %v", err)
		return nil, err
	}
	return permissions, nil
}

// GetPermissionsByRoleID 获取指定角色的权限
func GetPermissionsByRoleID(roleID uint) ([]models.Permission, error) {
	var permissions []models.Permission
	err := config.DB.Model(&models.Permission{}).
		Joins("JOIN role_permissions rp ON permissions.id = rp.permission_id").
		Where("rp.role_id = ? AND permissions.deleted_at = ?", roleID, 0).
		Find(&permissions).Error
	if err != nil {
		log.Printf("Error getting permissions by role id: %v", err)
		return nil, err
	}
	return permissions, nil
}

// BuildPermissionResponse 构建权限响应
func BuildPermissionResponse(permission *models.Permission) *models.PermissionResponse {
	return &models.PermissionResponse{
		ID:        permission.ID,
		Name:      permission.Name,
		Resource:  permission.Resource,
		Action:    permission.Action,
		CreatedAt: time.Unix(permission.CreatedAt, 0).Format("2006-01-02 15:04:05"),
		UpdatedAt: time.Unix(permission.UpdatedAt, 0).Format("2006-01-02 15:04:05"),
	}
}

// BuildPermissionsResponse 构建权限列表响应
func BuildPermissionsResponse(permissions []models.Permission) []models.PermissionResponse {
	var responses []models.PermissionResponse
	for _, p := range permissions {
		responses = append(responses, models.PermissionResponse{
			ID:        p.ID,
			Name:      p.Name,
			Resource:  p.Resource,
			Action:    p.Action,
			CreatedAt: time.Unix(p.CreatedAt, 0).Format("2006-01-02 15:04:05"),
			UpdatedAt: time.Unix(p.UpdatedAt, 0).Format("2006-01-02 15:04:05"),
		})
	}
	return responses
}
