package sresponse

import (
	"net/http"

	"github.com/tech/sendico/pkg/api/http/response"
	"github.com/tech/sendico/pkg/mlogger"
	"github.com/tech/sendico/pkg/model"
	"go.mongodb.org/mongo-driver/v2/bson"
)

type accountData struct {
	model.AccountPublic `json:",inline"`
	IsAnonymous         bool `json:"isAnonymous"`
}

type accountResponse struct {
	authResponse `json:",inline"`
	Account      accountData `json:"account"`
}

func _createAccount(account *model.Account, isAnonymous bool) *accountData {
	return &accountData{
		AccountPublic: account.AccountPublic,
		IsAnonymous:   isAnonymous,
	}
}

func _toAccount(account *model.Account, orgRef bson.ObjectID) *accountData {
	return _createAccount(account, model.AccountIsAnonymous(&account.UserDataBase, orgRef))
}

func Account(logger mlogger.Logger, account *model.Account, accessToken *TokenData) http.HandlerFunc {
	return response.Ok(
		logger,
		&accountResponse{
			Account:      *_createAccount(account, false),
			authResponse: authResponse{AccessToken: *accessToken},
		},
	)
}

type accountsResponse struct {
	authResponse `json:",inline"`
	Accounts     []accountData `json:"accounts"`
}

func Accounts(logger mlogger.Logger, accounts []model.Account, orgRef bson.ObjectID, accessToken *TokenData) http.HandlerFunc {
	// Convert each account to its public representation.
	publicAccounts := make([]accountData, len(accounts))
	for i, a := range accounts {
		publicAccounts[i] = *_toAccount(&a, orgRef)
	}

	return response.Ok(
		logger,
		&accountsResponse{
			Accounts:     publicAccounts,
			authResponse: authResponse{AccessToken: *accessToken},
		},
	)
}
