/*
 * Copyright 2026 Oleg Borodin <onborodin@gmail.com>
 */
package imageoper

import (
	"context"
	"fmt"
	"net/http"
	"strconv"

	"mstore/pkg/descr"

	ocidigest "github.com/opencontainers/go-digest"
)

type GetManifestParams struct {
	Name      string
	Reference string
}
type GetManifestResult struct {
	ContentLength       string
	ContentType         string
	DockerContentDigest string
	Payload             string
}

func (oper *Operator) GetManifest(ctx context.Context, params *GetManifestParams) (*GetManifestResult, int, error) {
	var err error
	res := &GetManifestResult{}

	if params.Name == "" {
		err = fmt.Errorf("Empty name")
		return res, http.StatusBadRequest, err
	}
	if params.Reference == "" {
		err = fmt.Errorf("Empty reference")
		return res, http.StatusBadRequest, err
	}

	resName := params.Name
	oper.iLock.WaitAndLock(resName)
	defer oper.iLock.Done(resName)

	manDescr := descr.Manifest{}
	var exists bool
	digobj, parseErr := ocidigest.Parse(params.Reference)
	if parseErr == nil {
		exists, manDescr, err = oper.mdb.GetManifestByDigest(ctx, params.Name, digobj.String())
		if err != nil {
			return res, http.StatusInternalServerError, err
		}
		if !exists {
			return res, http.StatusNotFound, err
		}
		res.DockerContentDigest = manDescr.Digest
		size := int64(len(manDescr.Payload))
		res.ContentLength = strconv.FormatInt(size, 10)
		res.ContentType = manDescr.ContentType
		res.Payload = manDescr.Payload

	} else {
		/*
			// Create index of manifests. Or not.
			exists, manDescrs, err := oper.mdb.GetManifestsByReference(ctx, params.Name, params.Reference)
			if err != nil {
				return res, http.StatusInternalServerError, err
			}
			if !exists {
				return res, http.StatusNotFound, err
			}
			if len(manDescrs) == 1 {
				manDescr = manDescrs[0]
				res.DockerContentDigest = manDescr.Digest
				size := int64(len(manDescr.Payload))
				res.ContentLength = strconv.FormatInt(size, 10)
				res.ContentType = manDescr.ContentType
				res.Payload = manDescr.Payload
			} else {
				_, indexdata, err := indexFromManigestDescrs(manDescrs)
				if err != nil {
					return res, http.StatusInternalServerError, err
				}
				digobj := ocidigest.FromBytes(indexdata)
				res.DockerContentDigest = digobj.String()

				size := int64(len(indexdata))
				res.ContentLength = strconv.FormatInt(size, 10)
				res.ContentType = oiiMediaType
				res.Payload = string(indexdata)
			}
		*/
		exists, manDescr, err := oper.mdb.GetManifestByReference(ctx, params.Name, params.Reference)
		if err != nil {
			return res, http.StatusInternalServerError, err
		}
		if !exists {
			return res, http.StatusNotFound, err
		}
		res.DockerContentDigest = manDescr.Digest
		size := int64(len(manDescr.Payload))
		res.ContentLength = strconv.FormatInt(size, 10)
		res.ContentType = manDescr.ContentType
		res.Payload = manDescr.Payload

	}
	return res, http.StatusOK, err
}
