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

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

type BlobExistsParams struct {
	Name   string
	Digest string
}
type BlobExistsResult struct {
	DockerContentDigest string
	ContentLength       string
	ContentType         string
}

func (oper *Operator) BlobExists(ctx context.Context, operatorID string, params *BlobExistsParams) (*BlobExistsResult, int, error) {
	var err error
	res := &BlobExistsResult{}

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

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

	// Check blob descriptor
	descrExists, blobDescr, err := oper.mdb.GetBlobByNameDigest(ctx, params.Name, params.Digest)
	if err != nil {
		return res, http.StatusInternalServerError, err
	}
	if !descrExists {
		return res, http.StatusNotFound, err
	}
	// Check blob file
	blobExists, _, err := oper.store.BlobExists(params.Name, params.Digest)
	if err != nil {
		return res, http.StatusInternalServerError, err
	}
	if !blobExists {
		return res, http.StatusNotFound, err
	}

	res.ContentLength = strconv.FormatInt(blobDescr.Size, 10)
	res.DockerContentDigest = blobDescr.Digest
	res.ContentType = blobDescr.MediaType

	return res, http.StatusOK, err
}
