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

import (
	"context"

	"mstore/pkg/descr"
)

type ListAccountsParams struct{}
type ListAccountsResult struct {
	Accounts []descr.AccountShort `json:"accounts"`
}

func (oper *Operator) ListAccounts(ctx context.Context, params *ListAccountsParams) (*ListAccountsResult, error) {
	var err error
	res := &ListAccountsResult{}

	accountDescrs, err := oper.mdb.ReducedListAccounts(ctx)
	if err != nil {
		return res, err
	}
	for _, accountDescr := range accountDescrs {
		accountShort := descr.AccountShort{
			ID:        accountDescr.ID,
			Username:  accountDescr.Username,
			Disabled:  accountDescr.Disabled,
			CreatedAt: accountDescr.CreatedAt,
			UpdatedAt: accountDescr.UpdatedAt,
			CreatedBy: accountDescr.CreatedBy,
			UpdatedBy: accountDescr.UpdatedBy,
			Grants:    make([]descr.Grant, 0),
		}
		grantDescrs, err := oper.mdb.ListGrantsByAccountID(ctx, accountDescr.ID)
		if err != nil {
			return res, err
		}
		accountShort.Grants = grantDescrs
		res.Accounts = append(res.Accounts, accountShort)
	}
	return res, err
}
