package main

import (
	"encoding/json"
	"fmt"
	"os"
	"time"

	"github.com/diamondburned/arikawa/v3/discord"
	"github.com/georgysavva/scany/pgxscan"
)

type Guild struct {
	ID              uint64
	Channels        map[string]discord.Snowflake
	Redirects       map[string]discord.Snowflake
	IgnoredChannels []uint64
	BannedSystems   []string
	KeyRoles        []uint64
	IgnoredUsers    []uint64
}

type Invite struct {
	GuildID uint64
	Code    string
	Name    string
}

type WatchlistEntry struct {
	GuildID   uint64
	UserID    uint64
	Moderator uint64
	Added     time.Time
	Reason    string
}

type GuildsExport struct {
	Guilds    []Guild
	Invites   []Invite
	Watchlist []WatchlistEntry
}

func exportGuilds() error {
	var guilds []Guild
	err := pgxscan.Select(ctx, conn, &guilds, "SELECT * FROM guilds")
	if err != nil {
		return err
	}

	var invites []Invite
	err = pgxscan.Select(ctx, conn, &invites, "SELECT * FROM invites")
	if err != nil {
		return err
	}

	var watchlist []WatchlistEntry
	err = pgxscan.Select(ctx, conn, &watchlist, "SELECT * FROM watchlist")
	if err != nil {
		return err
	}

	b, err := json.Marshal(GuildsExport{guilds, invites, watchlist})
	if err != nil {
		return err
	}

	filename := fmt.Sprintf("guilds-%v.json", time.Now().Unix())

	err = os.WriteFile(filename, b, 0o755)
	if err != nil {
		return err
	}

	return nil
}
