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

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

// FileInfo
type FileInfoParams struct {
	Filepath string
	Source   string
	Dest     string
}
type FileInfoResult struct {
	ContentCollection string
	ContentName       string
	ContentType       string
	ContentSize       string
	ContentDigest     string
	ContentCreatedAt  string
	ContentCreatedBy  string
	ContentUpdatedAt  string
	ContentUpdatedBy  string
}

func cleanFilepath(filename string) (string, error) {
	filename = "/" + filename
	return filepath.Clean(filename), nil
}

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

	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)

	exist, fileDescr, err := oper.mdb.GetFileByCollectionName(ctx, collection, filename)
	if err != nil {
		code := http.StatusInternalServerError
		return code, res, err
	}
	if !exist {
		code = http.StatusNotFound
		return code, res, err
	}
	res = &FileInfoResult{
		ContentCollection: fileDescr.Collection,
		ContentName:       fileDescr.Name,
		ContentSize:       strconv.FormatInt(fileDescr.Size, 10),
		ContentType:       fileDescr.Type,
		ContentDigest:     fileDescr.Checksum,

		ContentCreatedAt: fileDescr.CreatedAt,
		ContentCreatedBy: fileDescr.CreatedBy,
		ContentUpdatedAt: fileDescr.UpdatedAt,
		ContentUpdatedBy: fileDescr.UpdatedBy,
	}
	return code, res, err
}
