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

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

type DeleteBlobParams struct {
	Name   string
	Digest string
}
type DeleteBlobResult struct{}

// Removing an individual layer is very probably to compromise data integrity.
// - If the data layers are to be reused, this is like shooting yourself in the foot.
// - It also prevents the manifest from being issued, as one
// of the layers is missing.

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

	if params.Digest == "" {
		err = fmt.Errorf("Empty digest")
		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 namespace record
	descrExists, _, err := oper.mdb.GetBlobByNameDigest(ctx, params.Name, params.Digest)
	if err != nil {
		return res, http.StatusInternalServerError, err
	}

	if !descrExists {
		return res, http.StatusNotFound, err
	}
	// Deleting blob record
	oper.logg.Warningf("Deleting blob record %s:%s", params.Name, params.Digest)
	err = oper.mdb.DeleteBlobByNameDigest(ctx, params.Name, params.Digest)
	if err != nil {
		return res, http.StatusInternalServerError, err
	}
	// Removing the blob binary if usage == 0
	blobUsage, err := oper.mdb.GetBlobUsage(ctx, params.Name, params.Digest)
	if err != nil {
		return res, http.StatusInternalServerError, err
	}
	if blobUsage == 0 {
		oper.logg.Warningf("Deleting useless blob binary %s", params.Digest)
		oper.store.DeleteBlob(params.Name, params.Digest)
	}
	return res, http.StatusOK, err
}
