package nkode

import (
	"errors"
	"fmt"
	m "go-nkode/core/model"
)

type InMemoryDb struct {
	Customers map[m.CustomerId]m.Customer
	Users     map[m.UserId]m.User
	userIdMap map[string]m.UserId
}

func NewInMemoryDb() InMemoryDb {
	return InMemoryDb{
		Customers: make(map[m.CustomerId]m.Customer),
		Users:     make(map[m.UserId]m.User),
		userIdMap: make(map[string]m.UserId),
	}
}

func (db *InMemoryDb) GetCustomer(id m.CustomerId) (*m.Customer, error) {
	customer, exists := db.Customers[id]
	if !exists {
		return nil, errors.New(fmt.Sprintf("customer %s dne", customer.Id))
	}
	return &customer, nil
}

func (db *InMemoryDb) GetUser(username m.Username, customerId m.CustomerId) (*m.User, error) {
	key := userIdKey(customerId, username)
	userId, exists := db.userIdMap[key]
	if !exists {
		return nil, errors.New(fmt.Sprintf("customer %s with username %s dne", customerId, username))
	}
	user, exists := db.Users[userId]
	if !exists {
		panic(fmt.Sprintf("userId %s with customerId %s and username %s with no user", userId, customerId, username))
	}
	return &user, nil
}

func (db *InMemoryDb) WriteNewCustomer(customer m.Customer) error {
	_, exists := db.Customers[customer.Id]

	if exists {
		return errors.New(fmt.Sprintf("can write customer %s; already exists", customer.Id))
	}
	db.Customers[customer.Id] = customer
	return nil
}

func (db *InMemoryDb) WriteNewUser(user m.User) error {
	_, exists := db.Customers[user.CustomerId]
	if !exists {
		return errors.New(fmt.Sprintf("can't add user %s to customer %s: customer dne", user.Username, user.CustomerId))
	}
	userExists, _ := db.GetUser(user.Username, user.CustomerId)

	if userExists != nil {
		return errors.New(fmt.Sprintf("can't write new user %s, alread exists", user.Username))
	}
	key := userIdKey(user.CustomerId, user.Username)
	db.userIdMap[key] = user.Id
	db.Users[user.Id] = user
	return nil
}

func (db *InMemoryDb) UpdateUserInterface(userId m.UserId, ui m.UserInterface) error {
	user, exists := db.Users[userId]
	if !exists {
		return errors.New(fmt.Sprintf("can't update user %s, dne", user.Id))
	}
	user.Interface = ui
	return nil
}

func (db *InMemoryDb) Renew(id m.CustomerId) error {
	customer, exists := db.Customers[id]
	if !exists {
		return errors.New(fmt.Sprintf("customer %s does not exist", id))
	}
	setXor, attrsXor := customer.RenewKeys()
	db.Customers[id] = customer
	var err error
	for _, user := range db.Users {
		if user.CustomerId == id {
			err = user.RenewKeys(setXor, attrsXor)
			if err != nil {
				panic(err)
			}
			db.Users[user.Id] = user
		}
	}
	return nil
}

func (db *InMemoryDb) RefreshUser(user m.User, passocode []int, customerAttr m.CustomerAttributes) error {
	err := user.RefreshPasscode(passocode, customerAttr)
	if err != nil {
		return err
	}
	db.Users[user.Id] = user
	return nil
}

func userIdKey(customerId m.CustomerId, username m.Username) string {
	key := fmt.Sprintf("%s:%s", customerId, username)
	return key
}
