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"
	cid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/container/id"
	frostfscrypto "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/crypto"
	frostfsecdsa "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/crypto/ecdsa"
	"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/session"
)

// PrmContainerDelete groups parameters of ContainerDelete operation.
type PrmContainerDelete struct {
	// FrostFS request X-Headers
	XHeaders []string

	ContainerID *cid.ID

	Session *session.Container
}

// SetContainer sets identifier of the FrostFS container to be removed.
// Required parameter.
//
// Deprecated: Use PrmContainerDelete.Container instead.
func (prm *PrmContainerDelete) SetContainer(id cid.ID) {
	prm.ContainerID = &id
}

func (prm *PrmContainerDelete) buildRequest(c *Client) (*v2container.DeleteRequest, error) {
	if prm.ContainerID == nil {
		return nil, errorMissingContainer
	}

	if len(prm.XHeaders)%2 != 0 {
		return nil, errorInvalidXHeaders
	}

	var cidV2 refs.ContainerID
	prm.ContainerID.WriteToV2(&cidV2)

	// Container contract expects signature of container ID value,
	// don't get confused with stable marshaled protobuf container.ID structure.
	data := cidV2.GetValue()

	var sig frostfscrypto.Signature

	err := sig.Calculate(frostfsecdsa.SignerRFC6979(c.prm.Key), data)
	if err != nil {
		return nil, fmt.Errorf("calculate signature: %w", err)
	}

	var sigv2 refs.Signature
	sig.WriteToV2(&sigv2)

	reqBody := new(v2container.DeleteRequestBody)
	reqBody.SetContainerID(&cidV2)
	reqBody.SetSignature(&sigv2)

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

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

		meta.SetSessionToken(&tokv2)
	}

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

// WithinSession specifies session within which container should be removed.
//
// Creator of the session acquires the authorship of the request.
// This may affect the execution of an operation (e.g. access control).
//
// Must be signed.
//
// Deprecated: Use PrmContainerDelete.Session instead.
func (prm *PrmContainerDelete) WithinSession(tok session.Container) {
	prm.Session = &tok
}

// ResContainerDelete groups resulting values of ContainerDelete operation.
type ResContainerDelete struct {
	statusRes
}

// ContainerDelete sends request to remove the FrostFS container.
//
// 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`.
//
// Operation is asynchronous and no guaranteed even in the absence of errors.
// The required time is also not predictable.
//
// Success can be verified by reading by identifier (see GetContainer).
//
// Returns an error if parameters are set incorrectly (see PrmContainerDelete docs).
// Context is required and must not be nil. It is used for network communication.
//
// Exactly one return value is non-nil. Server status return is returned in ResContainerDelete.
// Reflects all internal errors in second return value (transport problems, response processing, etc.).
//
// Return statuses:
//   - global (see Client docs).
func (c *Client) ContainerDelete(ctx context.Context, prm PrmContainerDelete) (*ResContainerDelete, 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.DeleteContainer(&c.c, req, client.WithContext(ctx))
	if err != nil {
		return nil, err
	}

	var res ResContainerDelete
	res.st, err = c.processResponse(resp)
	return &res, err
}