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

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

// DeleteFile
type DeleteFileParams struct {
	Filepath string
}
type DeleteFileResult struct{}

func (oper *Operator) DeleteFile(ctx context.Context, operatorID string, params *DeleteFileParams) (int, *DeleteFileResult, error) {
	var err error
	res := &DeleteFileResult{}
	code := http.StatusOK

	xfilepath, err := cleanFilepath(params.Filepath)
	if err != nil {
		code := http.StatusInternalServerError
		return code, res, err
	}
	filename := path.Base(xfilepath)
	collection := path.Dir(xfilepath)

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

	descrExists, _, err := oper.mdb.GetFileByCollectionName(ctx, collection, filename)
	if err != nil {
		code = http.StatusInternalServerError
		return code, res, err
	}
	if !descrExists {
		code := http.StatusNotFound
		return code, res, err
	}

	if descrExists {
		err = oper.mdb.DeleteFileByCollectionName(ctx, collection, filename)
		if err != nil {
			code = http.StatusInternalServerError
			return code, res, err
		}
	}
	err = oper.store.DeleteFile(collection, filename)
	if err != nil {
		code = http.StatusInternalServerError
		return code, res, err
	}
	return code, res, err
}
