package main

import (
	// External
	werr "git.ahall.se/go/wrappederror"
	"github.com/jackc/pgx/v5"

	// Internal
	"smon/notification"

	// Standard
	"context"
	"database/sql"
	"encoding/json"
	"time"
)

type NotificationSend struct {
	Prio          int
	Service       string
	ID            int
	UUID          string
	Sent          time.Time `db:"send"`
	OK            bool
	Error         sql.NullString
	ErrorIndented string
	Acknowledged  bool
	TriggerName   string `db:"trigger_name"`
}

func notificationLog(notificationService *notification.Service, problemID int, err error) {
	if err == nil {
		logger.Info("notification", "service", (*notificationService).GetType(), "problemID", problemID, "prio", (*notificationService).GetPrio(), "ok", true)
		_, dbErr := db.Exec(
			context.Background(),
			`
			INSERT INTO notification_send()
			`,
		)
		if dbErr != nil {
			logger.Error("notification", "op", "notification_send", "error", werr.Wrap(err))
		}

	} else {
		logger.Error("notification", "service", (*notificationService).GetType(), "problemID", problemID, "prio", (*notificationService).GetPrio(), "ok", false, "error", err)
	}
}

func notificationsSent(from, to time.Time) (nss []NotificationSend, err error) {
	rows, _ := db.Query(
		context.Background(),
		`
		SELECT
			n.prio,
			n.service,
			
			COALESCE(t.name, '[NODATA]') AS trigger_name,
			
			ns.id,
			ns.uuid,
			ns.send,
			ns.ok,
			ns.error::varchar,
			ns.acknowledged
			
		FROM public.notification_send ns
		INNER JOIN notification n ON ns.notification_id = n.id
		LEFT JOIN problem p ON ns.problem_id = p.id
		LEFT JOIN "trigger" t ON p.trigger_id = t.id
		WHERE
			ns.send >= $1 AND
			ns.send <= $2
		
		ORDER BY
			send DESC
		`,
		from,
		to,
	)
	nss, err = pgx.CollectRows(rows, func(row pgx.CollectableRow) (ns NotificationSend, err error) {
		ns, err = pgx.RowToStructByName[NotificationSend](row)
		if err != nil {
			err = werr.Wrap(err)
			return
		}

		// Error contains json (can be NULL),
		// and can at least be presented indented.
		foo := make(map[string]any)
		json.Unmarshal([]byte(ns.Error.String), &foo)
		var j []byte
		j, err = json.MarshalIndent(foo, "", "    ")
		ns.ErrorIndented = string(j)

		return
	})
	if err != nil {
		err = werr.Wrap(err)
		return
	}

	return
}
