package permissions

import (
	"context"
	"fmt"
	"net/http"

	"fr.latosa-escrima/core"
	"fr.latosa-escrima/core/models"
	"github.com/jackc/pgtype"
)

type ResourceActions struct {
	Resource string           `bun:"resource" json:"resource"`
	Actions  pgtype.TextArray `bun:"actions" json:"actions"`
}

func HandleResourceActions(w http.ResponseWriter, r *http.Request) {
	var groupedPermissions []ResourceActions
	err := core.DB.NewSelect().
		Model((*models.Permission)(nil)).
		Column("resource").
		ColumnExpr("array_agg(action) AS actions").
		Group("resource").
		Scan(context.Background(), &groupedPermissions)

	fmt.Println(groupedPermissions)

	if err != nil {
		core.JSONError{
			Status:  core.Error,
			Message: err.Error(),
		}.Respond(w, http.StatusInternalServerError)
		return
	}

	result := make(map[string]interface{}, 0)

	for _, gp := range groupedPermissions {
		var actions []string

		_ = gp.Actions.AssignTo(&actions)

		result[gp.Resource] = actions
	}

	core.JSONSuccess{
		Status:  core.Success,
		Message: "Permissions found.",
		Data:    result,
	}.Respond(w, http.StatusOK)
}
