package osx

import (
	"io"
	"os"
)

// Copy copies a file from source to destination
func Copy(from, to string) (err error) {
	// Open the source file for reading
	srcFile, err := os.Open(from)
	if err != nil {
		return err
	}
	defer srcFile.Close()

	// Create the destination file for writing
	dstFile, err := os.Create(to)
	if err != nil {
		return err
	}
	// Closing may flush buffered writes, so its error must be surfaced — a
	// successful copy with a failed close means the destination is incomplete.
	// Defer the close and only let it overwrite the return value when the copy
	// itself succeeded; otherwise keep the first error.
	defer func() {
		cerr := dstFile.Close()
		if err == nil {
			err = cerr
		}
	}()

	// Use a buffer to copy the file in chunks
	buf := make([]byte, 1024*1024) // 1 MB buffer

	// Copy the data from srcFile to dstFile
	_, err = io.CopyBuffer(dstFile, srcFile, buf)
	if err != nil {
		return err
	}

	return nil
}
