package logs

import (
	"context"
	"encoding/json"

	"git.aiterp.net/rpdata/logbot3/internal/api"
	"git.aiterp.net/rpdata/logbot3/internal/models"
)

// SetOpen changes the open state of a log.
func SetOpen(ctx context.Context, log models.Log, open bool) (models.Log, error) {
	return edit(ctx, editInput{ID: log.ID, Open: &open})
}

// SetEventName changes the event name of a log.
func SetEventName(ctx context.Context, log models.Log, event string) (models.Log, error) {
	return edit(ctx, editInput{ID: log.ID, Event: &event})
}

func edit(ctx context.Context, input editInput) (models.Log, error) {
	data, err := api.Global().Query(ctx, editGQL, map[string]interface{}{"input": input}, []string{"log.edit"})
	if err != nil {
		return models.Log{}, err
	}

	res := editResult{}
	err = json.Unmarshal(data, &res)
	if err != nil {
		return models.Log{}, err
	}

	return res.Log, nil
}

type editResult struct {
	Log models.Log `json:"editLog"`
}

type editInput struct {
	ID          string  `json:"id"`
	Title       *string `json:"title"`
	Event       *string `json:"event"`
	Description *string `json:"description"`
	Open        *bool   `json:"open"`
}

const editGQL = `
	mutation EditLog($input:LogEditInput!) {
		editLog(input:$input) {
			id
			date
			channelName
			title
			eventName
			description
			open
			posts {
				id
				time
				kind
				nick
				text
			}
		}
	}
`