package system

import (
	"context"
	"errors"
)

// CasbinUsecase Casbin用例
type CasbinUsecase struct {
	repo          CasbinRepo
	authUc        *AuthorityUsecase
	apiUc         *ApiUsecase
	useStrictAuth bool
}

// NewCasbinUsecase 创建Casbin用例
func NewCasbinUsecase(repo CasbinRepo, authUc *AuthorityUsecase, apiUc *ApiUsecase) *CasbinUsecase {
	return &CasbinUsecase{
		repo:          repo,
		authUc:        authUc,
		apiUc:         apiUc,
		useStrictAuth: false,
	}
}

// UpdateCasbin 更新Casbin权限
func (uc *CasbinUsecase) UpdateCasbin(adminAuthorityID, authorityId uint, casbinInfos []struct {
	Path   string
	Method string
}) error {
	// 转换为 CasbinRule
	rules := make([]CasbinRule, len(casbinInfos))
	for i, info := range casbinInfos {
		rules[i] = CasbinRule{
			Path:   info.Path,
			Method: info.Method,
		}
	}

	return uc.repo.UpdateCasbin(adminAuthorityID, authorityId, rules)
}

// GetPolicyPathByAuthorityId 获取权限路径
func (uc *CasbinUsecase) GetPolicyPathByAuthorityId(authorityId uint) []CasbinRule {
	return uc.repo.GetPolicyPathByAuthorityId(authorityId)
}

// FreshCasbin 刷新Casbin缓存
func (uc *CasbinUsecase) FreshCasbin() error {
	return uc.repo.FreshCasbin()
}

// CheckPermission 检查权限
func (uc *CasbinUsecase) CheckPermission(ctx context.Context, sub, obj, act string) (bool, error) {
	// 这里可以添加权限检查逻辑
	return true, nil
}

// ClearCasbin 清除Casbin规则
func (uc *CasbinUsecase) ClearCasbin(v int, p ...string) bool {
	return uc.repo.ClearCasbin(v, p...)
}

// AddPolicies 添加策略
func (uc *CasbinUsecase) AddPolicies(rules [][]string) error {
	return uc.repo.AddPolicies(rules)
}

// RemoveFilteredPolicy 删除筛选的策略
func (uc *CasbinUsecase) RemoveFilteredPolicy(authorityId string) error {
	return uc.repo.RemoveFilteredPolicy(authorityId)
}

// SyncPolicy 同步策略（先删除再添加）
func (uc *CasbinUsecase) SyncPolicy(authorityId string, rules [][]string) error {
	return uc.repo.SyncPolicy(authorityId, rules)
}

// UpdateCasbinApi API更新随动
func (uc *CasbinUsecase) UpdateCasbinApi(oldPath, newPath, oldMethod, newMethod string) error {
	return uc.repo.UpdateCasbinApi(oldPath, newPath, oldMethod, newMethod)
}

// ValidateCasbinInfos 验证Casbin信息（严格模式）
func (uc *CasbinUsecase) ValidateCasbinInfos(ctx context.Context, adminAuthorityID uint, casbinInfos []CasbinRule) error {
	if !uc.useStrictAuth {
		return nil
	}

	apis, err := uc.apiUc.GetAllApis(ctx, adminAuthorityID)
	if err != nil {
		return err
	}

	for _, info := range casbinInfos {
		hasApi := false
		for _, api := range apis {
			if api.Path == info.Path && api.Method == info.Method {
				hasApi = true
				break
			}
		}
		if !hasApi {
			return errors.New("存在api不在权限列表中")
		}
	}

	return nil
}
