package nostr

import (
	"context"

	"git.devvul.com/asara/well-goknown/config"
	"github.com/fiatjaf/eventstore/postgresql"
	"github.com/fiatjaf/khatru"
	"github.com/fiatjaf/khatru/policies"
	"github.com/jmoiron/sqlx"
)

var (
	DB      *sqlx.DB
	RelayDb postgresql.PostgresBackend
	relay   *khatru.Relay
)

type nostrUser struct {
	Pubkey string  `db:"pubkey"`
	Relays *string `db:"relays,omitempty"`
}

type nostrWellKnown struct {
	Names  map[string]string   `json:"names"`
	Relays map[string][]string `json:"relays,omitempty"`
	NIP46  map[string][]string `json:"nip46,omitempty"`
}

func NewRelay(version string) *khatru.Relay {
	// relay configuration
	relay = khatru.NewRelay()
	relay.Info.Name = config.GetConfig().RelayName
	relay.Info.PubKey = config.GetConfig().RelayPubkey
	relay.Info.Description = config.GetConfig().RelayDescription
	relay.Info.Icon = config.GetConfig().RelayIcon
	relay.Info.Contact = config.GetConfig().RelayContact
	relay.Info.Version = version
	relay.Info.Software = "https://git.devvul.com/asara/well-goknown"

	relay.Info.SupportedNIPs = []any{
		1,  // basic protocol
		2,  // contact lists
		4,  // encrypted DMs
		11, // relay info
		42, // auth
		70, // protected events
	}

	relay.OnConnect = append(relay.OnConnect, func(ctx context.Context) {
		khatru.RequestAuth(ctx)
	})

	// storage
	relay.StoreEvent = append(relay.StoreEvent, RelayDb.SaveEvent)
	relay.QueryEvents = append(relay.QueryEvents, RelayDb.QueryEvents)
	relay.CountEvents = append(relay.CountEvents, RelayDb.CountEvents)
	relay.DeleteEvent = append(relay.DeleteEvent, RelayDb.DeleteEvent)
	relay.ReplaceEvent = append(relay.ReplaceEvent, RelayDb.ReplaceEvent)

	// apply policies
	relay.RejectEvent = append(relay.RejectEvent,
		RejectUnregisteredNpubs,
		policies.ValidateKind,
	)

	relay.RejectFilter = append(relay.RejectFilter,
		policies.RejectKind04Snoopers,
		policies.NoEmptyFilters,
		policies.NoComplexFilters,
	)

	return relay
}