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/user"
)

// PrmContainerList groups parameters of ContainerList operation.
type PrmContainerList struct {
	prmCommonMeta

	ownerSet bool
	ownerID  user.ID
}

// SetAccount sets identifier of the FrostFS account to list the containers.
// Required parameter.
func (x *PrmContainerList) SetAccount(id user.ID) {
	x.ownerID = id
	x.ownerSet = true
}

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

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

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

	var req v2container.ListRequest
	req.SetBody(reqBody)
	c.prepareRequest(&req, new(v2session.RequestMetaHeader))
	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.ResolveFrostFSFailures has been called, unsuccessful
// FrostFS status codes are returned as `error`, otherwise, are included
// in the returned result structure.
//
// 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
}