/*
 * Copyright 2026 Oleg Borodin <onborodin@gmail.com>
 */
package accoper

import (
	"context"
	"fmt"

	"mstore/pkg/auxpwd"
	"mstore/pkg/auxtool"
	"mstore/pkg/descr"
)

type UpdateAccountParams struct {
	Username    string `json:"username"`
	AccountID   string `json:"accountId"`
	NewUsername string `json:"newUsername"`
	NewPassword string `json:"newPassword"`
	Disabled    bool   `json:"disabled"`
}
type UpdateAccountResult struct{}

func (oper *Operator) UpdateAccount(ctx context.Context, operatorID string, params *UpdateAccountParams) (*UpdateAccountResult, error) {
	var err error
	res := &UpdateAccountResult{}
	if params.Username == "" && params.AccountID == "" {
		err := fmt.Errorf("Empty username and accountId parameter")
		return res, err
	}
	var accountDescr *descr.Account
	var accountExists bool
	switch {
	case params.AccountID != "":
		accountExists, accountDescr, err = oper.mdb.GetAccountByID(ctx, params.AccountID)
		if err != nil {
			return res, err
		}
		if !accountExists {
			err := fmt.Errorf("Account with ID %s dont exists", params.AccountID)
			return res, err
		}
	case params.Username != "":
		accountExists, accountDescr, err = oper.mdb.GetAccountByUsername(ctx, params.Username)
		if err != nil {
			return res, err
		}
		if !accountExists {
			err := fmt.Errorf("Account with name %s dont exists", params.Username)
			return res, err
		}
	default:
		err := fmt.Errorf("Empty username and accountId parameter")
		return res, err
	}
	if accountDescr == nil {
		err := fmt.Errorf("Null account desriptor")
		return res, err
	}
	now := auxtool.TimeNow()
	if params.NewUsername != "" {
		accountDescr.UpdatedAt = now
		accountDescr.Username = params.NewUsername
	}
	if params.NewPassword != "" {
		accountDescr.UpdatedAt = now
		passhash := auxpwd.MakeSHA256Hash([]byte(params.NewPassword))
		accountDescr.Passhash = passhash
	}
	if params.Disabled != accountDescr.Disabled {
		accountDescr.UpdatedAt = now
		accountDescr.Disabled = params.Disabled
	}

	err = oper.mdb.UpdateAccountByID(ctx, accountDescr.ID, accountDescr)
	if err != nil {
		return res, err
	}
	return res, err
}
