using System.CommandLine;
using NatsNet.PortTracker.Data;

namespace NatsNet.PortTracker.Commands;

public static class OverrideCommands
{
    public static Command Create(Option<string> dbOption)
    {
        var overrideCommand = new Command("override", "Review status override records");

        var typeOpt = new Option<string?>("--type")
        {
            Description = "Filter by table: features or tests"
        };

        var listCmd = new Command("list", "List all status overrides");
        listCmd.Add(typeOpt);
        listCmd.SetAction(parseResult =>
        {
            var dbPath = parseResult.GetValue(dbOption)!;
            var type = parseResult.GetValue(typeOpt);
            using var db = new Database(dbPath);

            var sql = "SELECT id, table_name, item_id, audit_status, requested_status, comment, created_at FROM status_overrides";
            var parameters = new List<(string, object?)>();

            if (type is not null)
            {
                var tableName = type switch
                {
                    "features" => "features",
                    "tests" => "unit_tests",
                    _ => type
                };
                sql += " WHERE table_name = @table";
                parameters.Add(("@table", tableName));
            }
            sql += " ORDER BY created_at DESC";

            var rows = db.Query(sql, parameters.ToArray());
            if (rows.Count == 0)
            {
                Console.WriteLine("No overrides found.");
                return;
            }

            Console.WriteLine($"{"ID",-5} {"Table",-12} {"Item",-6} {"Audit",-10} {"Requested",-10} {"Comment",-35} {"Date",-20}");
            Console.WriteLine(new string('-', 98));
            foreach (var row in rows)
            {
                Console.WriteLine($"{row["id"],-5} {row["table_name"],-12} {row["item_id"],-6} {row["audit_status"],-10} {row["requested_status"],-10} {Truncate(row["comment"]?.ToString(), 34),-35} {row["created_at"],-20}");
            }
            Console.WriteLine($"\nTotal: {rows.Count} overrides");
        });

        overrideCommand.Add(listCmd);
        return overrideCommand;
    }

    private static string Truncate(string? s, int maxLen)
    {
        if (s is null) return "";
        return s.Length <= maxLen ? s : s[..(maxLen - 2)] + "..";
    }
}
