using Moonlight.App.Database.Entities;
using Moonlight.App.Helpers;
using Moonlight.App.Models.Misc;
using Moonlight.App.Services;

namespace Moonlight.App.MalwareScans;

public class BadScriptsScan : MalwareScan
{
    public override string Name => "BadScripts Scan";
    public override string Description => "This scanner tries to find scripts like proxies or other bad stuff";
    public async override Task<MalwareScanResult?> Scan(Server server, IServiceProvider serviceProvider)
    {
        var serverService = serviceProvider.GetRequiredService<ServerService>();
        var fileAccess = await serverService.CreateFileAccess(server, null!);

        string[] fileExtensions =
        {
            ".py",
            ".js",
            ".json",
            ".txt",
            ".sh",
            ".env",
            ".md",
            ".html",
            ".htm"
        };

        string[] badWords =
        {
            "cloudscraper",
            "shadowsocks",
            "karma-ddos",
            "quake",
            "nuked by",
            "nuke bot",
            "t-e-s-tweb",
            "nezha",
            "rblxwild.com",
            "proxyscrape",
            "vless://",
            "vmess://",
            "trojan://",
            "shadowrocket",
            "urfate/afk-bot",
            "token vc spammer",
            "pretreer.com",
            "madfutters.com",
            "ultrafut",
            "selfcord.py",
            "https://github.com/go-gost/gost",
            "nodejs-proxy"
        };
        
        var files = await fileAccess.Ls();
        var filteredFiles = files.Where(x => 
            StringHelper.EndsInOneOf(x.Name, fileExtensions));

        foreach (var file in filteredFiles)
        {
            var content = await fileAccess.Read(file);
            var processableContent = content.ToLower();

            if (StringHelper.ContainsOneOf(processableContent, badWords, out string foundText))
            {
                return new()
                {
                    Title = "Software which is not allowed",
                    Description = $"Found bad word in script '{file.Name}': '{foundText}'",
                    Author = "Marcel Baumgartner"
                };
            }
        }

        return null;
    }
}