package main

import (
	"encoding/json"
	"net/http"
)

type Account struct {
	Username string `json:"username"`
	Password string `json:"password"`
	Email    string `json:"email"`
	// Cookies   []byte `json:"cookies"`

	Cookies   []*http.Cookie `json:"cookies"`
	Available bool           `json:"available"`
}

func GetAvailableAccounts() ([]Account, error) {

	data, count, err := client.From("accounts").Select("*", "exact", false).Eq("available", "true").Execute()

	if err != nil {
		return nil, err
	}

	//return count == 1, nil

	_ = count

	res := make([]Account, 0, count)
	if err := json.Unmarshal(data, &res); err != nil {
		return nil, err
	}

	return res, nil

}

// []*http.Cookie

func UpdateCookies(username string, cookies []*http.Cookie) error {

	res, _, err := client.From("accounts").Update(&struct {
		Cookies []*http.Cookie `json:"cookies"`
	}{
		Cookies: cookies,
	}, "", "exact").Eq("username", username).Execute()

	_ = res

	return err
}

func UpdateCookiesByBytes(username string, cookies []byte) error {

	res, _, err := client.From("accounts").Update(&struct {
		Cookies []byte `json:"cookies"`
	}{
		Cookies: cookies,
	}, "", "exact").Eq("username", username).Execute()

	_ = res

	return err
}

func SetNotAvailable(username string, errStr string) error {

	res, _, err := client.From("accounts").Update(&struct {
		// Error string `json:"error"`
		Error     string `json:"error"`
		Available bool   `json:"available"`
	}{
		Error:     errStr,
		Available: false,
	}, "", "exact").Eq("username", username).Execute()

	_ = res

	return err
}
