package client

import (
	"context"
	"crypto/ecdsa"
	"fmt"

	"git.frostfs.info/TrueCloudLab/frostfs-api-go/v2/acl"
	v2object "git.frostfs.info/TrueCloudLab/frostfs-api-go/v2/object"
	v2refs "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"
	"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/bearer"
	"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/checksum"
	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/object"
	oid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/object/id"
	"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/session"
)

// PrmObjectHash groups parameters of ObjectHash operation.
type PrmObjectHash struct {
	XHeaders []string

	BearerToken *bearer.Token

	Session *session.Object

	Local bool

	Ranges []object.Range

	Salt []byte

	ChecksumType checksum.Type

	ContainerID *cid.ID

	ObjectID *oid.ID

	Key *ecdsa.PrivateKey
}

// UseKey specifies private key to sign the requests.
// If key is not provided, then Client default key is used.
//
// Deprecated: Use PrmObjectHash.Key instead.
func (prm *PrmObjectHash) UseKey(key ecdsa.PrivateKey) {
	prm.Key = &key
}

// TillichZemorAlgo changes the hash function to Tillich-Zemor
// (https://link.springer.com/content/pdf/10.1007/3-540-48658-5_5.pdf).
//
// By default, SHA256 hash function is used/.
//
// Deprecated: Use PrmObjectHash.ChecksumType instead.
func (prm *PrmObjectHash) TillichZemorAlgo() {
	prm.ChecksumType = checksum.TZ
}

// ResObjectHash groups resulting values of ObjectHash operation.
type ResObjectHash struct {
	statusRes

	checksums [][]byte
}

// Checksums returns a list of calculated checksums in range order.
func (x ResObjectHash) Checksums() [][]byte {
	return x.checksums
}

func (prm *PrmObjectHash) buildRequest(c *Client) (*v2object.GetRangeHashRequest, error) {
	if prm.ContainerID == nil {
		return nil, errorMissingContainer
	}

	if prm.ObjectID == nil {
		return nil, errorMissingObject
	}

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

	if len(prm.Ranges) == 0 {
		return nil, errorMissingRanges
	}

	meta := new(v2session.RequestMetaHeader)
	writeXHeadersToMeta(prm.XHeaders, meta)

	if prm.BearerToken != nil {
		v2BearerToken := new(acl.BearerToken)
		prm.BearerToken.WriteToV2(v2BearerToken)
		meta.SetBearerToken(v2BearerToken)
	}

	if prm.Session != nil {
		v2SessionToken := new(v2session.Token)
		prm.Session.WriteToV2(v2SessionToken)
		meta.SetSessionToken(v2SessionToken)
	}

	if prm.Local {
		meta.SetTTL(1)
	}

	addr := new(v2refs.Address)

	cnrV2 := new(v2refs.ContainerID)
	prm.ContainerID.WriteToV2(cnrV2)
	addr.SetContainerID(cnrV2)

	objV2 := new(v2refs.ObjectID)
	prm.ObjectID.WriteToV2(objV2)
	addr.SetObjectID(objV2)

	rs := make([]v2object.Range, len(prm.Ranges))
	for i := range prm.Ranges {
		rs[i].SetOffset(prm.Ranges[i].GetOffset())
		rs[i].SetLength(prm.Ranges[i].GetLength())
	}

	body := new(v2object.GetRangeHashRequestBody)
	body.SetAddress(addr)
	body.SetRanges(rs)
	body.SetSalt(prm.Salt)

	if prm.ChecksumType == checksum.Unknown {
		body.SetType(v2refs.SHA256)
	} else {
		body.SetType(v2refs.ChecksumType(prm.ChecksumType))
	}

	req := new(v2object.GetRangeHashRequest)
	req.SetBody(body)
	c.prepareRequest(req, meta)

	return req, nil
}

// ObjectHash requests checksum of the range list of the object payload using
// FrostFS API protocol.
//
// Returns a list of checksums in raw form: the format of hashes and their number
// is left for the caller to check. Client preserves the order of the server's response.
//
// 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 PrmObjectHash docs).
// Context is required and must not be nil. It is used for network communication.
//
// Return statuses:
//   - global (see Client docs);
//   - *apistatus.ContainerNotFound;
//   - *apistatus.ObjectNotFound;
//   - *apistatus.ObjectAccessDenied;
//   - *apistatus.ObjectOutOfRange;
//   - *apistatus.SessionTokenExpired.
func (c *Client) ObjectHash(ctx context.Context, prm PrmObjectHash) (*ResObjectHash, error) {
	req, err := prm.buildRequest(c)
	if err != nil {
		return nil, err
	}

	key := c.prm.key
	if prm.Key != nil {
		key = *prm.Key
	}

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

	resp, err := rpcapi.HashObjectRange(&c.c, req, client.WithContext(ctx))
	if err != nil {
		return nil, fmt.Errorf("write request: %w", err)
	}

	var res ResObjectHash
	res.st, err = c.processResponse(resp)
	if err != nil {
		return nil, err
	}

	if !apistatus.IsSuccessful(res.st) {
		return &res, nil
	}

	res.checksums = resp.GetBody().GetHashList()
	if len(res.checksums) == 0 {
		return nil, newErrMissingResponseField("hash list")
	}

	return &res, nil
}