package service

import (
	"net/url"
	"path/filepath"
	"strings"
)

var dangerousExtensions = map[string]bool{
	".exe": true, ".bat": true, ".cmd": true, ".scr": true,
	".js": true, ".vbs": true, ".com": true, ".ps1": true,
	".sh": true, ".wsf": true, ".wsh": true, ".msi": true,
	".dll": true, ".lnk": true, ".inf": true, ".reg": true,
	".vbe": true, ".jse": true, ".cpl": true, ".hta": true,
}

type SafetyBlockResult struct {
	Blocked          bool   `json:"blocked"`
	Reason           string `json:"reason"`
	MatchedExtension string `json:"matched_extension"`
}

type SafetyService struct{}

func NewSafetyService() *SafetyService {
	return &SafetyService{}
}

func (s *SafetyService) Check(title string, downloadURL string) *SafetyBlockResult {
	// Check extension from release title
	ext := strings.ToLower(filepath.Ext(title))
	if dangerousExtensions[ext] {
		return &SafetyBlockResult{
			Blocked:          true,
			Reason:           "Release contains dangerous file extension: " + ext,
			MatchedExtension: ext,
		}
	}

	// Check extension from download URL
	if downloadURL != "" {
		u, err := url.Parse(downloadURL)
		if err == nil {
			urlExt := strings.ToLower(filepath.Ext(u.Path))
			if dangerousExtensions[urlExt] {
				return &SafetyBlockResult{
					Blocked:          true,
					Reason:           "Download URL contains dangerous file extension: " + urlExt,
					MatchedExtension: urlExt,
				}
			}
		}
	}

	return nil
}
