package cli

import (
	"context"
	"fmt"
	"time"

	"github.com/spf13/cobra"

	"git.cloudinit.dev/coreci/orca/internal/store"
)

var (
	auditLimit int
)

var auditCmd = &cobra.Command{
	Use:   "audit",
	Short: "View orca audit log",
	Long:  "Display the most recent audit log entries (security-first observability).",
}

var auditListCmd = &cobra.Command{
	Use:   "list",
	Short: "List recent audit log entries",
	RunE: func(cmd *cobra.Command, args []string) error {
		ctx, cancel := context.WithTimeout(cmd.Context(), 5*time.Second)
		defer cancel()

		db, closer, err := openDB()
		if err != nil {
			return err
		}
		defer closer()

		entries, err := store.NewAuditRepo(db).List(ctx, auditLimit)
		if err != nil {
			return err
		}
		if jsonOutput {
			return printJSON(entries)
		}
		if len(entries) == 0 {
			fmt.Fprintln(cmd.OutOrStdout(), "No audit entries.")
			return nil
		}
		fmt.Fprintf(cmd.OutOrStdout(), "%-22s  %-12s  %-20s  %-30s  %-10s\n", "TIMESTAMP", "ACTOR", "ACTION", "RESOURCE", "RESULT")
		for _, e := range entries {
			fmt.Fprintf(cmd.OutOrStdout(), "%-22s  %-12s  %-20s  %-30s  %-10s\n",
				e.Timestamp.Format("2006-01-02T15:04:05Z"), e.Actor, e.Action, e.Resource, e.Result)
		}
		return nil
	},
}

func init() {
	auditListCmd.Flags().IntVar(&auditLimit, "limit", 50, "max entries to show")
	auditCmd.AddCommand(auditListCmd)
	rootCmd.AddCommand(auditCmd)
}
