package main

import (
	"errors"
	"fmt"
	"os"
	"strconv"
	"time"

	"database/sql"

	"git.tilde.town/tildetown/town/towndb"

	_ "github.com/mattn/go-sqlite3"
)

type dbs struct {
	Invites *sql.DB
	Signups *sql.DB
	Users   *sql.DB
}

func connect() (*dbs, error) {
	users, err := sql.Open("sqlite3", "/town/var/town.db?mode=r")
	if err != nil {
		return nil, err
	}

	signups, err := sql.Open("sqlite3", "/town/var/signups/signups.db?mode=r")
	if err != nil {
		return nil, err
	}

	invites, err := sql.Open("sqlite3", "/town/var/invites/invites.db?mode=r")
	if err != nil {
		return nil, err
	}

	return &dbs{
		Invites: invites,
		Signups: signups,
		Users:   users,
	}, nil
}

func _main(argv []string) error {
	if len(argv) < 3 {
		return errors.New("want two args (user|email) <lookup>")
	}

	switch argv[1] {
	case "user":
		return userLookup(argv[2])
	case "email":
		return emailLookup(argv[2])
	default:
		return fmt.Errorf("idk %s", argv[2])
	}
}

func userLookup(username string) error {
	dbs, err := connect()
	if err != nil {
		return err
	}

	stmt, err := dbs.Users.Prepare("SELECT id,created,username,state,admin FROM users WHERE username = ?")
	if err != nil {
		return fmt.Errorf("user select prepare failed: %w", err)
	}
	var created string
	tu := towndb.TownUser{}
	err = stmt.QueryRow(username).Scan(&tu.ID, &created, &tu.Username, &tu.State, &tu.IsAdmin)
	if err != nil {
		return fmt.Errorf("failed to select user: %w", err)
	}
	i, err := strconv.ParseInt(created, 10, 64)
	if err != nil {
		return fmt.Errorf("time what? %w", err)
	}
	tu.Created = time.Unix(i, 0)

	fmt.Println("id,created,username,state,admin")
	fmt.Printf("%d,%s,%s,%s,%v\n", tu.ID, tu.Created, tu.Username, tu.State, tu.IsAdmin)

	// TODO rest

	return nil
}

func emailLookup(address string) error {
	// TODO
	return nil
}

func main() {
	if err := _main(os.Args); err != nil {
		fmt.Fprintf(os.Stderr, "error: %s\n", err.Error())
		os.Exit(1)
	}
}
