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

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

type GetBlobParams struct {
	Name   string
	Digest string
}
type GetBlobResult struct {
	ContentLength       string
	ContentType         string
	DockerContentDigest string
	ReadCloser          io.ReadCloser
}

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

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

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

	blobExists, blobSize, err := oper.store.BlobExists(params.Name, params.Digest)
	if err != nil {
		return res, http.StatusInternalServerError, err
	}
	descrExist, blobDescr, err := oper.mdb.GetBlobByNameDigest(ctx, params.Name, params.Digest)
	if err != nil {
		return res, http.StatusInternalServerError, err
	}
	if !blobExists || !descrExist {
		return res, http.StatusNotFound, err
	}

	_, readCloser, err := oper.store.BlobReader(params.Name, params.Digest)
	if err != nil {
		return res, http.StatusInternalServerError, err
	}

	res.ContentType = blobDescr.MediaType
	res.ContentLength = strconv.FormatInt(blobSize, 10)
	res.DockerContentDigest = params.Digest
	res.ReadCloser = readCloser
	return res, http.StatusOK, err
}
