BIN_DIR      		  := $(CURDIR)/bin
APP_NAME     	      ?= molva-app-backend
VERSION      		  ?= $(shell git describe --tags 2>/dev/null || echo "v0.0.0")
BUILD_DATE			  := $(shell date -u +'%Y-%m-%dT%H:%M:%SZ')
GIT_COMMIT   		  := $(shell git rev-parse HEAD 2>/dev/null)
LDFLAGS      		  := "-s -w -X main.version=$(VERSION) -X main.commit=$(GIT_COMMIT) -X main.date=$(BUILD_DATE)"
GOLANGCI_LINT_VERSION := v1.62.2
ENV 				  := "local"
UNAME_S 			  := $(shell uname -s)
CONFIG_PATH           := .build/config/

ifeq ($(OS),Windows_NT)
    CONFIG_PATH := $(subst /,\,$(CONFIG_PATH))
endif

.PHONY: all
all: lint build

## -- Dependency Management --
.PHONY: install-tools
install-tools: $(BIN_DIR)/golangci-lint

.PHONY: $(BIN_DIR)/golangci-lint
$(BIN_DIR)/golangci-lint:
	@mkdir -p $(@D)
	@echo "Installing golangci-lint $(GOLANGCI_LINT_VERSION)..."
	@GOBIN=$(BIN_DIR) go install github.com/golangci/golangci-lint/cmd/golangci-lint@$(GOLANGCI_LINT_VERSION)

## -- Linting --
.PHONY: lint
lint: $(BIN_DIR)/golangci-lint
	@echo "Running linter..."
	@$(BIN_DIR)/golangci-lint run --config .golangci-lint.yaml --fix=false --color=always

## -- Run --
## To change env use: make run CONFIG_PATH={config file dir path} ENV={env}
.PHONY: run
run:
	@echo "Starting $(APP_NAME)..."
	@echo CGO_ENABLED=0 go run -ldflags=$(LDFLAGS) ./cmd/main.go --config_path=$(CONFIG_PATH) --env=$(ENV)
	@CGO_ENABLED=0 go run -ldflags=$(LDFLAGS) ./cmd/main.go --config_path=$(CONFIG_PATH) --env=$(ENV)

## -- Building --
.PHONY: build
build: build-linux build-darwin build-windows

# Build for Linux
.PHONY: build-linux
build-linux:
	@echo "Building for Linux..."
	@GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -ldflags=$(LDFLAGS) -o $(BIN_DIR)/$(APP_NAME)_linux_amd64 ./cmd/main.go
	@GOOS=linux GOARCH=arm64 CGO_ENABLED=0 go build -ldflags=$(LDFLAGS) -o $(BIN_DIR)/$(APP_NAME)_linux_arm64 ./cmd/main.go

# Build for macOS (Darwin)
.PHONY: build-darwin
build-darwin:
	@echo "Building for macOS..."
	@GOOS=darwin GOARCH=amd64 CGO_ENABLED=0 go build -ldflags=$(LDFLAGS) -o $(BIN_DIR)/$(APP_NAME)_darwin_amd64 ./cmd/main.go
	@GOOS=darwin GOARCH=arm64 CGO_ENABLED=0 go build -ldflags=$(LDFLAGS) -o $(BIN_DIR)/$(APP_NAME)_darwin_arm64 ./cmd/main.go

# Build for Windows
.PHONY: build-windows
build-windows:
	@echo "Building for Windows..."
	@GOOS=windows GOARCH=amd64 CGO_ENABLED=0 go build -ldflags=$(LDFLAGS) -o $(BIN_DIR)/$(APP_NAME)_windows_amd64.exe ./cmd/main.go
	@GOOS=windows GOARCH=arm64 CGO_ENABLED=0 go build -ldflags=$(LDFLAGS) -o $(BIN_DIR)/$(APP_NAME)_windows_arm64.exe ./cmd/main.go

## -- Docker --
.PHONY: docker-build
docker-build:
	@echo "Building Docker image..."
	@docker build \
	    --build-arg BUILD_LDFLAGS=$(LDFLAGS) \
	    --build-arg CONFIG_FILE_PATH="$(CONFIG_PATH)$(ENV).yaml" \
	    -t $(APP_NAME):$(VERSION) \
	    .

## -- Cleanup --
.PHONY: clean
clean:
	@echo "Cleaning..."
	@rm -rf $(BIN_DIR)