package controllers

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"strings"

	"cloud.o-forge.io/core/oc-lib/config"
	beego "github.com/beego/beego/v2/server/web"
)

// Operations about workflow
type LokiController struct {
	beego.Controller
}

type LokiInfo struct {
	Start string `json:"start"`
	End   string `json:"end"`
}

// @Title GetLogs
// @Description get logs
// @Param	body		body 	models.compute	true		"The compute content"
// @Success 200 {workspace} models.workspace
// @router / [post]
func (o *LokiController) GetLogs() {
	path := "/loki/api/v1/query_range"
	var resp map[string]interface{}
	json.Unmarshal(o.Ctx.Input.CopyBody(100000), &resp)
	if len(resp) > 0 {
		start := fmt.Sprintf("%v", resp["start"])
		if len(start) > 10 {
			start = start[0:10]
		}
		end := fmt.Sprintf("%v", resp["end"])
		if len(end) > 10 {
			end = end[0:10]
		}
		query := []string{}
		for k, v := range resp {
			if k == "start" || k == "end" {
				continue
			}
			query = append(query, fmt.Sprintf("%v=\"%v\"", k, v))
		}
		if len(query) == 0 || len(start) < 10 || len(end) < 10 {
			o.Ctx.ResponseWriter.WriteHeader(403)
			o.Data["json"] = map[string]string{"error": "Query error, missing data : start, end or query"}
			o.ServeJSON()
			return
		}
		path += "?query={" + strings.Join(query, ", ") + "}&start=" + start + "&end=" + end
		resp, err := http.Get(config.GetConfig().LokiUrl + path) // CALL
		fmt.Println(resp, path)
		if err != nil {
			o.Ctx.ResponseWriter.WriteHeader(422)
			o.Data["json"] = map[string]string{"error": err.Error()}
			o.ServeJSON()
			return
		}
		defer resp.Body.Close()
		body, _ := io.ReadAll(resp.Body)
		var result map[string]interface{}
		// Unmarshal: string → []byte → object
		err = json.Unmarshal(body, &result)
		if err != nil {
			o.Ctx.ResponseWriter.WriteHeader(403)
			o.Data["json"] = map[string]string{"error": err.Error()}
			o.ServeJSON()
			return
		}
		o.Data["json"] = result
		o.ServeJSON()
		return
	}
	o.Ctx.ResponseWriter.WriteHeader(403)
	o.Data["json"] = map[string]string{"error": "Query error"}
	o.ServeJSON()
}
