package client

import (
	"context"
	"fmt"

	v2container "git.frostfs.info/TrueCloudLab/frostfs-api-go/v2/container"
	"git.frostfs.info/TrueCloudLab/frostfs-api-go/v2/refs"
	rpcapi "git.frostfs.info/TrueCloudLab/frostfs-api-go/v2/rpc"
	"git.frostfs.info/TrueCloudLab/frostfs-api-go/v2/rpc/client"
	v2session "git.frostfs.info/TrueCloudLab/frostfs-api-go/v2/session"
	"git.frostfs.info/TrueCloudLab/frostfs-api-go/v2/signature"
	apistatus "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/client/status"
	cid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/container/id"
	"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/session"
	"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/user"
)

// PrmContainerList groups parameters of ContainerList operation.
type PrmContainerList struct {
	XHeaders []string

	Account user.ID

	Session *session.Container
}

// SetAccount sets identifier of the FrostFS account to list the containers.
// Required parameter.
//
// Deprecated: Use PrmContainerList.Account instead.
func (x *PrmContainerList) SetAccount(id user.ID) {
	x.Account = id
}

func (x *PrmContainerList) buildRequest(c *Client) (*v2container.ListRequest, error) {
	if x.Account.IsEmpty() {
		return nil, errorAccountNotSet
	}

	var ownerV2 refs.OwnerID
	x.Account.WriteToV2(&ownerV2)

	reqBody := new(v2container.ListRequestBody)
	reqBody.SetOwnerID(&ownerV2)

	var meta v2session.RequestMetaHeader
	writeXHeadersToMeta(x.XHeaders, &meta)

	if x.Session != nil {
		var tokv2 v2session.Token
		x.Session.WriteToV2(&tokv2)

		meta.SetSessionToken(&tokv2)
	}

	var req v2container.ListRequest
	req.SetBody(reqBody)
	c.prepareRequest(&req, &meta)
	return &req, nil
}

// ResContainerList groups resulting values of ContainerList operation.
type ResContainerList struct {
	statusRes

	ids []cid.ID
}

// Containers returns list of identifiers of the account-owned containers.
//
// Client doesn't retain value so modification is safe.
func (x ResContainerList) Containers() []cid.ID {
	return x.ids
}

// ContainerList requests identifiers of the account-owned containers.
//
// Exactly one return value is non-nil. By default, server status is returned in res structure.
// Any client's internal or transport errors are returned as `error`.
// If PrmInit.DisableFrostFSFailuresResolution has been called, unsuccessful
// FrostFS status codes are included in the returned result structure,
// otherwise, are also returned as `error`.
//
// Returns an error if parameters are set incorrectly (see PrmContainerList docs).
// Context is required and must not be nil. It is used for network communication.
//
// Return statuses:
//   - global (see Client docs).
func (c *Client) ContainerList(ctx context.Context, prm PrmContainerList) (*ResContainerList, error) {
	req, err := prm.buildRequest(c)
	if err != nil {
		return nil, err
	}

	if err := signature.SignServiceMessage(&c.prm.Key, req); err != nil {
		return nil, fmt.Errorf("sign request: %w", err)
	}

	resp, err := rpcapi.ListContainers(&c.c, req, client.WithContext(ctx))
	if err != nil {
		return nil, err
	}

	var res ResContainerList
	res.st, err = c.processResponse(resp)
	if err != nil || !apistatus.IsSuccessful(res.st) {
		return &res, err
	}

	res.ids = make([]cid.ID, len(resp.GetBody().GetContainerIDs()))
	for i, cidV2 := range resp.GetBody().GetContainerIDs() {
		if err := res.ids[i].ReadFromV2(cidV2); err != nil {
			return &res, fmt.Errorf("invalid ID in the response: %w", err)
		}
	}

	return &res, nil
}