package acmanager

import (
	"encoding/json"
	"github.com/supabase-community/supabase-go"
	"net/http"
)

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

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

func (a Account) Stop() {
	// todo: stop the account.
}

type Manager struct {
	localUser map[string]Account
}

func NewManager() *Manager {
	return &Manager{
		localUser: make(map[string]Account),
	}
}

func (m *Manager) Init() error {
	user, err := GetAllAccounts()
	if err != nil {
		return err
	}
	for _, v := range user {
		m.localUser[v.Username] = v
	}
	return nil
}

func (m *Manager) AddUser(account Account) {
	if account.Available {
		m.addAvailable(account)
	} else {
		m.addInAvailable(account)
	}
}

func (m *Manager) addAvailable(account Account) {
	// todo: add to available
}

func (m *Manager) addInAvailable(account Account) {
	// todo: add to inavailable.
	// do login to check if the account is available.
	// if available, add to available.
	//sc := twitterscraper.New()

}

func (m *Manager) UpdateUser() {
	dbuser := make(map[string]Account)
	accounts, err := GetAllAccounts()
	if err != nil {
		return
	}
	for _, v := range accounts {
		dbuser[v.Username] = v
	}

	for k, v := range m.localUser {
		if _, ok := dbuser[k]; !ok {
			delete(m.localUser, k)
		}
		// delete the account, and stop the account.
		v.Stop()
	}
	for k, v := range dbuser {
		if _, ok := m.localUser[k]; !ok {
			m.localUser[k] = v
		}
	}
}

func GetAllAccounts() ([]Account, error) {
	// todo: get client from db.
	var client *supabase.Client
	data, count, err := client.From("accounts").Select("*", "exact", false).Execute()
	//data, count, err := client.From("accounts").Select("*", "exact", false).Eq("available", "true").Execute()

	if err != nil {
		return nil, err
	}

	_ = count

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

	return res, nil

}
