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

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

	Container *container.Container

	Session *session.Container
}

// SetContainer sets structured information about new FrostFS container.
// Required parameter.
//
// Deprecated: Use PrmContainerPut.Container instead.
func (x *PrmContainerPut) SetContainer(cnr container.Container) {
	x.Container = &cnr
}

// WithinSession specifies session within which container should be saved.
//
// Creator of the session acquires the authorship of the request. This affects
// the execution of an operation (e.g. access control).
//
// Session is optional, if set the following requirements apply:
//   - session operation MUST be session.VerbContainerPut (ForVerb)
//   - token MUST be signed using private key of the owner of the container to be saved
//
// Deprecated: Use PrmContainerPut.Session instead.
func (x *PrmContainerPut) WithinSession(s session.Container) {
	x.Session = &s
}

func (x *PrmContainerPut) buildRequest(c *Client) (*v2container.PutRequest, error) {
	if x.Container == nil {
		return nil, errorMissingContainer
	}

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

	// TODO: check private key is set before forming the request
	var cnr v2container.Container
	x.Container.WriteToV2(&cnr)

	var sig frostfscrypto.Signature

	err := container.CalculateSignature(&sig, *x.Container, c.prm.key)
	if err != nil {
		return nil, fmt.Errorf("calculate container signature: %w", err)
	}

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

	reqBody := new(v2container.PutRequestBody)
	reqBody.SetContainer(&cnr)
	reqBody.SetSignature(&sigv2)

	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.PutRequest
	req.SetBody(reqBody)
	c.prepareRequest(&req, &meta)
	return &req, nil
}

// ResContainerPut groups resulting values of ContainerPut operation.
type ResContainerPut struct {
	statusRes

	id cid.ID
}

// ID returns identifier of the container declared to be stored in the system.
// Used as a link to information about the container (in particular, you can
// asynchronously check if the save was successful).
func (x ResContainerPut) ID() cid.ID {
	return x.id
}

// ContainerPut sends request to save container in FrostFS.
//
// 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.
//
// 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 ResContainerPut.ID).
//
// Returns an error if parameters are set incorrectly (see PrmContainerPut docs).
// Context is required and must not be nil. It is used for network communication.
//
// Return statuses:
//   - global (see Client docs).
//
// nolint: funlen
func (c *Client) ContainerPut(ctx context.Context, prm PrmContainerPut) (*ResContainerPut, 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.PutContainer(&c.c, req, client.WithContext(ctx))
	if err != nil {
		return nil, err
	}

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

	const fieldCnrID = "container ID"

	cidV2 := resp.GetBody().GetContainerID()
	if cidV2 == nil {
		return &res, newErrMissingResponseField(fieldCnrID)
	}
	if err := res.id.ReadFromV2(*cidV2); err != nil {
		return &res, newErrInvalidResponseField(fieldCnrID, err)
	}
	return &res, nil
}