package gzip

import (
	"bufio"
	"compress/gzip"
	"io"
	"os"

	"golang.org/x/xerrors"

	"github.com/aquasecurity/trivy/pkg/fanal/utils"
)

// multiCloser wraps a reader and manages multiple closers for proper cleanup
type multiCloser struct {
	io.Reader
	closers []io.Closer
}

func (mc *multiCloser) Close() error {
	for _, c := range mc.closers {
		if err := c.Close(); err != nil {
			return err
		}
	}
	return nil
}

// OpenFile opens a file (optionally gzipped) by file path
func OpenFile(fileName string) (io.ReadCloser, error) {
	f, err := os.Open(fileName)
	if err != nil {
		return nil, xerrors.Errorf("unable to open the file: %w", err)
	}

	mc := &multiCloser{
		closers: []io.Closer{f},
	}

	br := bufio.NewReader(f)
	mc.Reader = br

	if utils.IsGzip(br) {
		gzr, err := gzip.NewReader(br)
		if err != nil {
			_ = f.Close()
			return nil, xerrors.Errorf("failed to open gzip: %w", err)
		}
		mc.Reader = gzr
		mc.closers = append(mc.closers, gzr)
	}

	return mc, nil
}
