# GoChat Makefile
# Reference: Chatwoot Makefile pattern (setup, db, server, docker, run)

APP_NAME := gochat
GO_ENV ?= development

# Go build flags
LDFLAGS := -s -w
BUILD_DIR := ./bin

# Targets
.PHONY: all setup build run dev test lint clean docker db_create db_migrate db_seed db_reset migrate help

all: build

## setup: Install dependencies
setup:
	go mod download
	go mod tidy

## build: Compile the binary
build:
	go build -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(APP_NAME) ./cmd/gochat/

## run: Run the compiled binary
run: build
	./$(BUILD_DIR)/$(APP_NAME)

## dev: Run in development mode with hot reload (requires air)
dev:
	air -c .air.toml

## test: Run tests
test:
	go test -v -race ./...

## test-cover: Run tests with coverage
test-cover:
	go test -v -race -coverprofile=coverage.out ./...
	go tool cover -html=coverage.out -o coverage.html

## lint: Run golangci-lint
lint:
	golangci-lint run ./...

## clean: Remove build artifacts
clean:
	rm -rf $(BUILD_DIR)
	rm -f coverage.out coverage.html

## docker: Build Docker image
docker:
	docker build -t $(APP_NAME) .

## db_create: Create database (ref: Chatwoot make db_create)
db_create:
	@echo "Creating database..."
	GOCHAT_ENV=$(GO_ENV) ./scripts/migrate.sh create

## db_migrate: Run migrations (ref: Chatwoot make db_migrate)
db_migrate:
	@echo "Running migrations..."
	GOCHAT_ENV=$(GO_ENV) ./scripts/migrate.sh up

## db_seed: Seed data (ref: Chatwoot make db_seed)
db_seed:
	@echo "Seeding database..."
	GOCHAT_ENV=$(GO_ENV) ./scripts/seed.sh

## db_reset: Reset database (ref: Chatwoot make db_reset)
db_reset:
	@echo "Resetting database..."
	GOCHAT_ENV=$(GO_ENV) ./scripts/migrate.sh down
	GOCHAT_ENV=$(GO_ENV) ./scripts/migrate.sh up
	GOCHAT_ENV=$(GO_ENV) ./scripts/seed.sh

## migrate: Create a new migration file
migrate:
	@read -p "Migration name: " name; 	migrate create -ext sql -dir migrations -seq $$name

## help: Show this help
help:
	@echo "GoChat Makefile Commands:"
	@echo ""
	@grep -E '^## ' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ": "}; {printf "\033[36m%-20s\033[0m %s\n", $$1, $$2}' | sed 's/## //g'
