package admin

import (
	"arimelody-web/admin/templates"
	"arimelody-web/log"
	"arimelody-web/model"
	"fmt"
	"net/http"
	"os"
	"strings"
)

func logsHandler(app *model.AppState) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        if r.Method != http.MethodGet {
            http.NotFound(w, r)
            return
        }

        session := r.Context().Value("session").(*model.Session)

        levelFilter := []log.LogLevel{}
        typeFilter := []string{}

        query := r.URL.Query().Get("q")

        for key, value := range r.URL.Query() {
            if strings.HasPrefix(key, "level-") && value[0] == "on" {
                m := map[string]log.LogLevel{
                    "info": log.LEVEL_INFO,
                    "warn": log.LEVEL_WARN,
                }
                level, ok := m[strings.TrimPrefix(key, "level-")]
                if ok {
                    levelFilter = append(levelFilter, level)
                }
                continue
            }

            if strings.HasPrefix(key, "type-") && value[0] == "on" {
                typeFilter = append(typeFilter, string(strings.TrimPrefix(key, "type-")))
                continue
            }
        }

        logs, err := app.Log.Search(levelFilter, typeFilter, query, 100, 0)
        if err != nil {
            fmt.Fprintf(os.Stderr, "WARN: Failed to fetch audit logs: %v\n", err)
            http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
            return
        }

        type LogsResponse struct {
            Session *model.Session
            Logs []*log.Log
        }

        err = templates.LogsTemplate.Execute(w, LogsResponse{
            Session: session,
            Logs: logs,
        })
        if err != nil {
            fmt.Fprintf(os.Stderr, "WARN: Failed to render audit logs page: %v\n", err)
            http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
            return
        }
    })
}
