/*
 * Copyright 2026 Oleg Borodin <onborodin@gmail.com>
 *
 * This work is published and licensed under a Creative Commons
 * Attribution-NonCommercial-NoDerivatives 4.0 International License.
 *
 * Distribution of this work is permitted, but commercial use and
 * modifications are strictly prohibited.
 */
package imageoper

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

	"mstore/pkg/auxoci"
	"mstore/pkg/descr"
)

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 manifest descr.Manifest
	manifests := make([]descr.Manifest, 0)
	var exists bool
	if stringLikeSHA256Digest(params.Reference) {
		digest := fmt.Sprintf("%s:%s", sha256prefix, params.Reference)
		exists, manifest, err = oper.mdb.GetManifestByDigest(ctx, params.Name, digest)
		if err != nil {
			return res, http.StatusInternalServerError, err
		}
		if !exists {
			return res, http.StatusNotFound, err
		}
	} else {
		exists, manifests, err = oper.mdb.GetManifestsByReference(ctx, params.Name, params.Reference)
		if err != nil {
			return res, http.StatusInternalServerError, err
		}
		if !exists {
			return res, http.StatusNotFound, err
		}
		manifest = manifests[0] // TODO: tmp
	}

	digest := auxoci.SHA256DigestFromString(manifest.Payload)
	payloadSize := len(manifest.Payload)
	res.ContentLength = strconv.FormatInt(int64(payloadSize), 10)
	res.ContentType = manifest.ContentType
	res.DockerContentDigest = digest.String()
	res.Exists = exists

	return res, http.StatusOK, err
}
