package smb2

import (
	"errors"
	"fmt"
	"os"

	"github.com/cloudsoda/go-smb2/internal/erref"
)

// status errors - add more if necessary

// ErrRequestNotAccepted happens when the host cannot accept more connections.
var ErrRequestNotAccepted = errors.New(erref.STATUS_REQUEST_NOT_ACCEPTED.Error())

// TransportError represents a error come from net.Conn layer.
type TransportError struct {
	Err error
}

func (err *TransportError) Error() string {
	return fmt.Sprintf("connection error: %v", err.Err)
}

// InternalError represents internal error.
type InternalError struct {
	Message string
}

func (err *InternalError) Error() string {
	return fmt.Sprintf("internal error: %s", err.Message)
}

// InvalidResponseError represents a data sent by the server is corrupted or unexpected.
type InvalidResponseError struct {
	Message string
}

func (err *InvalidResponseError) Error() string {
	return fmt.Sprintf("invalid response error: %s", err.Message)
}

// ResponseError represents a error with a nt status code sent by the server.
// The NTSTATUS is defined in [MS-ERREF].
// https://msdn.microsoft.com/en-au/library/cc704588.aspx
type ResponseError struct {
	Code uint32 // NTSTATUS
	data [][]byte
}

func (err *ResponseError) Error() string {
	return fmt.Sprintf("response error: %v", erref.NtStatus(err.Code))
}

// isFileDeleted reports whether err indicates a file was deleted or is pending
// deletion. This is used to silently skip directory entries that vanish between
// Readdir and a subsequent compound security query.
func isFileDeleted(err error) bool {
	var re *ResponseError
	return errors.Is(err, os.ErrNotExist) ||
		(errors.As(err, &re) && re.Code == uint32(erref.STATUS_DELETE_PENDING))
}
