/*
 * 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 ManifestExistsParams struct {
	Name      string
	Reference string
}
type ManifestExistsResult struct {
	ContentLength       string
	ContentType         string
	DockerContentDigest string
	Exists              bool
}

func (oper *Operator) ManifestExists(ctx context.Context, params *ManifestExistsParams) (*ManifestExistsResult, int, error) {
	var err error
	res := &ManifestExistsResult{}

	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
	}

	var man descr.Manifest
	var exist bool

	digobj, parseErr := ocidigest.Parse(params.Reference)
	if parseErr == nil {
		exist, man, err = oper.mdb.GetManifestByDigest(ctx, params.Name, digobj.String())
		if err != nil {
			return res, http.StatusInternalServerError, err
		}
		if !exist {
			return res, http.StatusNotFound, err
		}
		size := int64(len(man.Payload))
		res.ContentLength = strconv.FormatInt(size, 10)
		res.ContentType = man.ContentType
		res.DockerContentDigest = man.Digest
		res.Exists = exist
	} else {
		/*
					// Create index of manifests
					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
					} 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.Exists = true
			                }
		*/
		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
	}
	return res, http.StatusOK, err
}
