using System.CommandLine;
using System.CommandLine.Parsing;
using ScadaLink.Commons.Messages.Management;

namespace ScadaLink.CLI.Commands;

public static class AuditLogCommands
{
    public static Command Build(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
    {
        var command = new Command("audit-log") { Description = "Query audit logs" };

        command.Add(BuildQuery(urlOption, formatOption, usernameOption, passwordOption));

        return command;
    }

    private static Command BuildQuery(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
    {
        var userOption = new Option<string?>("--user") { Description = "Filter by username" };
        var entityTypeOption = new Option<string?>("--entity-type") { Description = "Filter by entity type" };
        var actionOption = new Option<string?>("--action") { Description = "Filter by action" };
        var fromOption = new Option<DateTimeOffset?>("--from") { Description = "Start date (ISO 8601)" };
        var toOption = new Option<DateTimeOffset?>("--to") { Description = "End date (ISO 8601)" };
        var pageOption = new Option<int>("--page") { Description = "Page number" };
        pageOption.DefaultValueFactory = _ => 1;
        var pageSizeOption = new Option<int>("--page-size") { Description = "Page size" };
        pageSizeOption.DefaultValueFactory = _ => 50;

        var cmd = new Command("query") { Description = "Query audit log entries" };
        cmd.Add(userOption);
        cmd.Add(entityTypeOption);
        cmd.Add(actionOption);
        cmd.Add(fromOption);
        cmd.Add(toOption);
        cmd.Add(pageOption);
        cmd.Add(pageSizeOption);
        cmd.SetAction(async (ParseResult result) =>
        {
            var user = result.GetValue(userOption);
            var entityType = result.GetValue(entityTypeOption);
            var action = result.GetValue(actionOption);
            var from = result.GetValue(fromOption);
            var to = result.GetValue(toOption);
            var page = result.GetValue(pageOption);
            var pageSize = result.GetValue(pageSizeOption);
            return await CommandHelpers.ExecuteCommandAsync(
                result, urlOption, formatOption, usernameOption, passwordOption,
                new QueryAuditLogCommand(user, entityType, action, from, to, page, pageSize));
        });
        return cmd;
    }
}
