<go_file>
<go_version> go1.21
<go_pkg> controllers

// controllers/patientController.go
// Pattern: struct controller + constructor injection + Swagger annotations
// Observed in: Medical-App-Core/controllers/
package controllers

import (
	"net/http"
	"time"

	"medical-sas-api/services/contracts"
	"github.com/gofiber/fiber/v2"
)

// PatientController handles HTTP requests for the Patient resource.
type PatientController struct {
	PatientService contracts.PatientServiceContract
}

// NewPatientController constructs a PatientController with its service dependency.
func NewPatientController(svc contracts.PatientServiceContract) *PatientController {
	return &PatientController{PatientService: svc}
}

// CreatePatient godoc
// @Summary     Create a new patient
// @Description Create a new patient in the system
// @Tags        Patients
// @Accept      json
// @Produce     json
// @Security    BearerAuth
// @Param       body body contracts.PatientInputDTO true "Patient data"
// @Success     201  {object} fiber.Map
// @Failure     400  {object} fiber.Map
// @Failure     422  {object} fiber.Map
// @Failure     500  {object} fiber.Map
// @Router      /patients [post]
func (ctrl *PatientController) CreatePatient(c *fiber.Ctx) error {
	var input contracts.PatientInputDTO
	if err := c.BodyParser(&input); err != nil {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "invalid request payload"})
	}

	if input.Name == "" {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "name is required"})
	}
	if input.Contact == "" {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "contact is required"})
	}

	id, err := ctrl.PatientService.CreateFromInput(input)
	if err != nil {
		return c.Status(http.StatusUnprocessableEntity).JSON(fiber.Map{"error": err.Error()})
	}

	return c.Status(http.StatusCreated).JSON(fiber.Map{
		"message": "Patient created successfully",
		"id":      id,
	})
}

// GetByCPF godoc
// @Summary     Get patient by CPF
// @Description Retrieve a single patient identified by its CPF
// @Tags        Patients
// @Produce     json
// @Security    BearerAuth
// @Param       cpf path string true "Patient CPF"
// @Success     200 {object} contracts.PatientDTO
// @Failure     400 {object} fiber.Map
// @Failure     404 {object} fiber.Map
// @Router      /patients/{cpf} [get]
func (ctrl *PatientController) GetByCPF(c *fiber.Ctx) error {
	identifier := c.Params("cpf")
	if identifier == "" {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "cpf is required"})
	}

	result, err := ctrl.PatientService.FindByCPF(identifier)
	if err != nil {
		return c.Status(http.StatusNotFound).JSON(fiber.Map{"error": err.Error()})
	}

	return c.Status(http.StatusOK).JSON(result)
}

// ListPatients godoc
// @Summary     List all patients
// @Description Returns a paginated list of patients
// @Tags        Patients
// @Produce     json
// @Security    BearerAuth
// @Param       page  query int false "Page number (default 1)"
// @Param       limit query int false "Page size (default 20)"
// @Success     200  {array}  contracts.PatientDTO
// @Failure     500  {object} fiber.Map
// @Router      /patients [get]
func (ctrl *PatientController) ListPatients(c *fiber.Ctx) error {
	page  := c.QueryInt("page", 1)
	limit := c.QueryInt("limit", 20)
	if page < 1  { page = 1 }
	if limit < 1 { limit = 20 }

	results, err := ctrl.PatientService.List(page, limit)
	if err != nil {
		return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"error": "failed to retrieve patients"})
	}

	return c.Status(http.StatusOK).JSON(fiber.Map{
		"data":  results,
		"page":  page,
		"limit": limit,
	})
}
</go_file>


<go_file>
<go_version> go1.21
<go_pkg> main

// cmd/main.go — Fiber router setup
// Pattern: group-based routing + auth middleware + Swagger protection
// Observed in: Medical-App-Core/cmd/main.go
package main

import (
	"log"
	"os"

	"medical-sas-api/controllers"
	"medical-sas-api/initializers"
	_ "medical-sas-api/docs"

	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/basicauth"
	"github.com/gofiber/fiber/v2/middleware/cors"
	"github.com/gofiber/fiber/v2/middleware/logger"
	"github.com/gofiber/swagger"
	"github.com/joho/godotenv"
)

// bearerAuthMiddleware validates the Authorization: Bearer <token> header.
// Returns 401 if missing or invalid; calls Next() on success.
func bearerAuthMiddleware(svc *initializers.Services) fiber.Handler {
	return func(c *fiber.Ctx) error {
		header := c.Get("Authorization")
		if len(header) <= 7 || header[:7] != "Bearer " {
			return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
				"error": "missing or malformed Authorization header",
			})
		}
		if err := svc.AuthTokenService.ValidateToken(header[7:]); err != nil {
			return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
				"error":  "invalid or expired token",
				"reason": err.Error(),
			})
		}
		return c.Next()
	}
}

func configureMiddleware(app *fiber.App) {
	app.Use(cors.New(cors.Config{
		AllowOrigins: "*",
		AllowMethods: "GET,POST,PUT,PATCH,DELETE,OPTIONS",
		AllowHeaders: "Origin, Content-Type, Accept, Authorization",
	}))
	app.Use(logger.New(logger.Config{
		Format: `[$\{time\}] $\{status\} - $\{method\} $\{path\}\n`,
	}))
}

func registerRoutes(app *fiber.App, svc *initializers.Services) {
	auth := app.Group("/auth")
	auth.Post("/token",    controllers.NewAuthController(svc.AuthTokenService).GenerateToken)
	auth.Post("/validate", controllers.NewAuthController(svc.AuthTokenService).ValidateToken)

	protected := app.Group("/", bearerAuthMiddleware(svc))

	entityCtrl := controllers.NewPatientController(svc.PatientService)
	patients := protected.Group("/patients")
	patients.Post("/",              entityCtrl.CreatePatient)
	patients.Get("/",               entityCtrl.ListPatients)
	patients.Get("/:cpf",   entityCtrl.GetByCPF)
}

func main() {
	if err := godotenv.Load(); err != nil {
		log.Println("warning: .env file not found, using environment")
	}

	db  := initializers.InitialDB()
	initializers.RunMigrations(db)
	svc := initializers.InitServices(db)

	app := fiber.New(fiber.Config{AppName: "medical-sas-api v1"})
	configureMiddleware(app)

	// Swagger endpoint protected by basic auth
	swaggerUser := os.Getenv("SWAGGER_USER")
	swaggerPass := os.Getenv("SWAGGER_PASSWORD")
	if swaggerUser == "" || swaggerPass == "" {
		log.Fatal("SWAGGER_USER and SWAGGER_PASSWORD must be set")
	}
	swaggerAuth := basicauth.New(basicauth.Config{
		Users: map[string]string{swaggerUser: swaggerPass},
	})
	app.Get("/swagger/*", swaggerAuth, swagger.HandlerDefault)

	registerRoutes(app, svc)

	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}
	log.Printf("server listening on :%s", port)
	if err := app.Listen(":" + port); err != nil {
		log.Fatalf("server error: %v", err)
	}
}
</go_file>


<go_file>
<go_version> go1.22
<go_pkg> controllers

// controllers/patientController.go
// Pattern: struct controller + constructor injection + Swagger annotations
// Observed in: Medical-App-Core/controllers/
package controllers

import (
	"net/http"
	"time"

	"medical-sas-api/services/contracts"
	"github.com/gofiber/fiber/v2"
)

// PatientController handles HTTP requests for the Patient resource.
type PatientController struct {
	PatientService contracts.PatientServiceContract
}

// NewPatientController constructs a PatientController with its service dependency.
func NewPatientController(svc contracts.PatientServiceContract) *PatientController {
	return &PatientController{PatientService: svc}
}

// CreatePatient godoc
// @Summary     Create a new patient
// @Description Create a new patient in the system
// @Tags        Patients
// @Accept      json
// @Produce     json
// @Security    BearerAuth
// @Param       body body contracts.PatientInputDTO true "Patient data"
// @Success     201  {object} fiber.Map
// @Failure     400  {object} fiber.Map
// @Failure     422  {object} fiber.Map
// @Failure     500  {object} fiber.Map
// @Router      /patients [post]
func (ctrl *PatientController) CreatePatient(c *fiber.Ctx) error {
	var input contracts.PatientInputDTO
	if err := c.BodyParser(&input); err != nil {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "invalid request payload"})
	}

	if input.Name == "" {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "name is required"})
	}
	if input.Contact == "" {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "contact is required"})
	}

	id, err := ctrl.PatientService.CreateFromInput(input)
	if err != nil {
		return c.Status(http.StatusUnprocessableEntity).JSON(fiber.Map{"error": err.Error()})
	}

	return c.Status(http.StatusCreated).JSON(fiber.Map{
		"message": "Patient created successfully",
		"id":      id,
	})
}

// GetByCPF godoc
// @Summary     Get patient by CPF
// @Description Retrieve a single patient identified by its CPF
// @Tags        Patients
// @Produce     json
// @Security    BearerAuth
// @Param       cpf path string true "Patient CPF"
// @Success     200 {object} contracts.PatientDTO
// @Failure     400 {object} fiber.Map
// @Failure     404 {object} fiber.Map
// @Router      /patients/{cpf} [get]
func (ctrl *PatientController) GetByCPF(c *fiber.Ctx) error {
	identifier := c.Params("cpf")
	if identifier == "" {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "cpf is required"})
	}

	result, err := ctrl.PatientService.FindByCPF(identifier)
	if err != nil {
		return c.Status(http.StatusNotFound).JSON(fiber.Map{"error": err.Error()})
	}

	return c.Status(http.StatusOK).JSON(result)
}

// ListPatients godoc
// @Summary     List all patients
// @Description Returns a paginated list of patients
// @Tags        Patients
// @Produce     json
// @Security    BearerAuth
// @Param       page  query int false "Page number (default 1)"
// @Param       limit query int false "Page size (default 20)"
// @Success     200  {array}  contracts.PatientDTO
// @Failure     500  {object} fiber.Map
// @Router      /patients [get]
func (ctrl *PatientController) ListPatients(c *fiber.Ctx) error {
	page  := c.QueryInt("page", 1)
	limit := c.QueryInt("limit", 20)
	if page < 1  { page = 1 }
	if limit < 1 { limit = 20 }

	results, err := ctrl.PatientService.List(page, limit)
	if err != nil {
		return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"error": "failed to retrieve patients"})
	}

	return c.Status(http.StatusOK).JSON(fiber.Map{
		"data":  results,
		"page":  page,
		"limit": limit,
	})
}
</go_file>


<go_file>
<go_version> go1.22
<go_pkg> main

// cmd/main.go — Fiber router setup
// Pattern: group-based routing + auth middleware + Swagger protection
// Observed in: Medical-App-Core/cmd/main.go
package main

import (
	"log"
	"os"

	"medical-sas-api/controllers"
	"medical-sas-api/initializers"
	_ "medical-sas-api/docs"

	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/basicauth"
	"github.com/gofiber/fiber/v2/middleware/cors"
	"github.com/gofiber/fiber/v2/middleware/logger"
	"github.com/gofiber/swagger"
	"github.com/joho/godotenv"
)

// bearerAuthMiddleware validates the Authorization: Bearer <token> header.
// Returns 401 if missing or invalid; calls Next() on success.
func bearerAuthMiddleware(svc *initializers.Services) fiber.Handler {
	return func(c *fiber.Ctx) error {
		header := c.Get("Authorization")
		if len(header) <= 7 || header[:7] != "Bearer " {
			return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
				"error": "missing or malformed Authorization header",
			})
		}
		if err := svc.AuthTokenService.ValidateToken(header[7:]); err != nil {
			return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
				"error":  "invalid or expired token",
				"reason": err.Error(),
			})
		}
		return c.Next()
	}
}

func configureMiddleware(app *fiber.App) {
	app.Use(cors.New(cors.Config{
		AllowOrigins: "*",
		AllowMethods: "GET,POST,PUT,PATCH,DELETE,OPTIONS",
		AllowHeaders: "Origin, Content-Type, Accept, Authorization",
	}))
	app.Use(logger.New(logger.Config{
		Format: `[$\{time\}] $\{status\} - $\{method\} $\{path\}\n`,
	}))
}

func registerRoutes(app *fiber.App, svc *initializers.Services) {
	auth := app.Group("/auth")
	auth.Post("/token",    controllers.NewAuthController(svc.AuthTokenService).GenerateToken)
	auth.Post("/validate", controllers.NewAuthController(svc.AuthTokenService).ValidateToken)

	protected := app.Group("/", bearerAuthMiddleware(svc))

	entityCtrl := controllers.NewPatientController(svc.PatientService)
	patients := protected.Group("/patients")
	patients.Post("/",              entityCtrl.CreatePatient)
	patients.Get("/",               entityCtrl.ListPatients)
	patients.Get("/:cpf",   entityCtrl.GetByCPF)
}

func main() {
	if err := godotenv.Load(); err != nil {
		log.Println("warning: .env file not found, using environment")
	}

	db  := initializers.InitialDB()
	initializers.RunMigrations(db)
	svc := initializers.InitServices(db)

	app := fiber.New(fiber.Config{AppName: "medical-sas-api v1"})
	configureMiddleware(app)

	// Swagger endpoint protected by basic auth
	swaggerUser := os.Getenv("SWAGGER_USER")
	swaggerPass := os.Getenv("SWAGGER_PASSWORD")
	if swaggerUser == "" || swaggerPass == "" {
		log.Fatal("SWAGGER_USER and SWAGGER_PASSWORD must be set")
	}
	swaggerAuth := basicauth.New(basicauth.Config{
		Users: map[string]string{swaggerUser: swaggerPass},
	})
	app.Get("/swagger/*", swaggerAuth, swagger.HandlerDefault)

	registerRoutes(app, svc)

	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}
	log.Printf("server listening on :%s", port)
	if err := app.Listen(":" + port); err != nil {
		log.Fatalf("server error: %v", err)
	}
}
</go_file>


<go_file>
<go_version> go1.23
<go_pkg> controllers

// controllers/patientController.go
// Pattern: struct controller + constructor injection + Swagger annotations
// Observed in: Medical-App-Core/controllers/
package controllers

import (
	"net/http"
	"time"

	"medical-sas-api/services/contracts"
	"github.com/gofiber/fiber/v2"
)

// PatientController handles HTTP requests for the Patient resource.
type PatientController struct {
	PatientService contracts.PatientServiceContract
}

// NewPatientController constructs a PatientController with its service dependency.
func NewPatientController(svc contracts.PatientServiceContract) *PatientController {
	return &PatientController{PatientService: svc}
}

// CreatePatient godoc
// @Summary     Create a new patient
// @Description Create a new patient in the system
// @Tags        Patients
// @Accept      json
// @Produce     json
// @Security    BearerAuth
// @Param       body body contracts.PatientInputDTO true "Patient data"
// @Success     201  {object} fiber.Map
// @Failure     400  {object} fiber.Map
// @Failure     422  {object} fiber.Map
// @Failure     500  {object} fiber.Map
// @Router      /patients [post]
func (ctrl *PatientController) CreatePatient(c *fiber.Ctx) error {
	var input contracts.PatientInputDTO
	if err := c.BodyParser(&input); err != nil {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "invalid request payload"})
	}

	if input.Name == "" {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "name is required"})
	}
	if input.Contact == "" {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "contact is required"})
	}

	id, err := ctrl.PatientService.CreateFromInput(input)
	if err != nil {
		return c.Status(http.StatusUnprocessableEntity).JSON(fiber.Map{"error": err.Error()})
	}

	return c.Status(http.StatusCreated).JSON(fiber.Map{
		"message": "Patient created successfully",
		"id":      id,
	})
}

// GetByCPF godoc
// @Summary     Get patient by CPF
// @Description Retrieve a single patient identified by its CPF
// @Tags        Patients
// @Produce     json
// @Security    BearerAuth
// @Param       cpf path string true "Patient CPF"
// @Success     200 {object} contracts.PatientDTO
// @Failure     400 {object} fiber.Map
// @Failure     404 {object} fiber.Map
// @Router      /patients/{cpf} [get]
func (ctrl *PatientController) GetByCPF(c *fiber.Ctx) error {
	identifier := c.Params("cpf")
	if identifier == "" {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "cpf is required"})
	}

	result, err := ctrl.PatientService.FindByCPF(identifier)
	if err != nil {
		return c.Status(http.StatusNotFound).JSON(fiber.Map{"error": err.Error()})
	}

	return c.Status(http.StatusOK).JSON(result)
}

// ListPatients godoc
// @Summary     List all patients
// @Description Returns a paginated list of patients
// @Tags        Patients
// @Produce     json
// @Security    BearerAuth
// @Param       page  query int false "Page number (default 1)"
// @Param       limit query int false "Page size (default 20)"
// @Success     200  {array}  contracts.PatientDTO
// @Failure     500  {object} fiber.Map
// @Router      /patients [get]
func (ctrl *PatientController) ListPatients(c *fiber.Ctx) error {
	page  := c.QueryInt("page", 1)
	limit := c.QueryInt("limit", 20)
	if page < 1  { page = 1 }
	if limit < 1 { limit = 20 }

	results, err := ctrl.PatientService.List(page, limit)
	if err != nil {
		return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"error": "failed to retrieve patients"})
	}

	return c.Status(http.StatusOK).JSON(fiber.Map{
		"data":  results,
		"page":  page,
		"limit": limit,
	})
}
</go_file>


<go_file>
<go_version> go1.23
<go_pkg> main

// cmd/main.go — Fiber router setup
// Pattern: group-based routing + auth middleware + Swagger protection
// Observed in: Medical-App-Core/cmd/main.go
package main

import (
	"log"
	"os"

	"medical-sas-api/controllers"
	"medical-sas-api/initializers"
	_ "medical-sas-api/docs"

	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/basicauth"
	"github.com/gofiber/fiber/v2/middleware/cors"
	"github.com/gofiber/fiber/v2/middleware/logger"
	"github.com/gofiber/swagger"
	"github.com/joho/godotenv"
)

// bearerAuthMiddleware validates the Authorization: Bearer <token> header.
// Returns 401 if missing or invalid; calls Next() on success.
func bearerAuthMiddleware(svc *initializers.Services) fiber.Handler {
	return func(c *fiber.Ctx) error {
		header := c.Get("Authorization")
		if len(header) <= 7 || header[:7] != "Bearer " {
			return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
				"error": "missing or malformed Authorization header",
			})
		}
		if err := svc.AuthTokenService.ValidateToken(header[7:]); err != nil {
			return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
				"error":  "invalid or expired token",
				"reason": err.Error(),
			})
		}
		return c.Next()
	}
}

func configureMiddleware(app *fiber.App) {
	app.Use(cors.New(cors.Config{
		AllowOrigins: "*",
		AllowMethods: "GET,POST,PUT,PATCH,DELETE,OPTIONS",
		AllowHeaders: "Origin, Content-Type, Accept, Authorization",
	}))
	app.Use(logger.New(logger.Config{
		Format: `[$\{time\}] $\{status\} - $\{method\} $\{path\}\n`,
	}))
}

func registerRoutes(app *fiber.App, svc *initializers.Services) {
	auth := app.Group("/auth")
	auth.Post("/token",    controllers.NewAuthController(svc.AuthTokenService).GenerateToken)
	auth.Post("/validate", controllers.NewAuthController(svc.AuthTokenService).ValidateToken)

	protected := app.Group("/", bearerAuthMiddleware(svc))

	entityCtrl := controllers.NewPatientController(svc.PatientService)
	patients := protected.Group("/patients")
	patients.Post("/",              entityCtrl.CreatePatient)
	patients.Get("/",               entityCtrl.ListPatients)
	patients.Get("/:cpf",   entityCtrl.GetByCPF)
}

func main() {
	if err := godotenv.Load(); err != nil {
		log.Println("warning: .env file not found, using environment")
	}

	db  := initializers.InitialDB()
	initializers.RunMigrations(db)
	svc := initializers.InitServices(db)

	app := fiber.New(fiber.Config{AppName: "medical-sas-api v1"})
	configureMiddleware(app)

	// Swagger endpoint protected by basic auth
	swaggerUser := os.Getenv("SWAGGER_USER")
	swaggerPass := os.Getenv("SWAGGER_PASSWORD")
	if swaggerUser == "" || swaggerPass == "" {
		log.Fatal("SWAGGER_USER and SWAGGER_PASSWORD must be set")
	}
	swaggerAuth := basicauth.New(basicauth.Config{
		Users: map[string]string{swaggerUser: swaggerPass},
	})
	app.Get("/swagger/*", swaggerAuth, swagger.HandlerDefault)

	registerRoutes(app, svc)

	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}
	log.Printf("server listening on :%s", port)
	if err := app.Listen(":" + port); err != nil {
		log.Fatalf("server error: %v", err)
	}
}
</go_file>


<go_file>
<go_version> go1.24
<go_pkg> controllers

// controllers/patientController.go
// Pattern: struct controller + constructor injection + Swagger annotations
// Observed in: Medical-App-Core/controllers/
package controllers

import (
	"net/http"
	"time"

	"medical-sas-api/services/contracts"
	"github.com/gofiber/fiber/v2"
)

// PatientController handles HTTP requests for the Patient resource.
type PatientController struct {
	PatientService contracts.PatientServiceContract
}

// NewPatientController constructs a PatientController with its service dependency.
func NewPatientController(svc contracts.PatientServiceContract) *PatientController {
	return &PatientController{PatientService: svc}
}

// CreatePatient godoc
// @Summary     Create a new patient
// @Description Create a new patient in the system
// @Tags        Patients
// @Accept      json
// @Produce     json
// @Security    BearerAuth
// @Param       body body contracts.PatientInputDTO true "Patient data"
// @Success     201  {object} fiber.Map
// @Failure     400  {object} fiber.Map
// @Failure     422  {object} fiber.Map
// @Failure     500  {object} fiber.Map
// @Router      /patients [post]
func (ctrl *PatientController) CreatePatient(c *fiber.Ctx) error {
	var input contracts.PatientInputDTO
	if err := c.BodyParser(&input); err != nil {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "invalid request payload"})
	}

	if input.Name == "" {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "name is required"})
	}
	if input.Contact == "" {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "contact is required"})
	}

	id, err := ctrl.PatientService.CreateFromInput(input)
	if err != nil {
		return c.Status(http.StatusUnprocessableEntity).JSON(fiber.Map{"error": err.Error()})
	}

	return c.Status(http.StatusCreated).JSON(fiber.Map{
		"message": "Patient created successfully",
		"id":      id,
	})
}

// GetByCPF godoc
// @Summary     Get patient by CPF
// @Description Retrieve a single patient identified by its CPF
// @Tags        Patients
// @Produce     json
// @Security    BearerAuth
// @Param       cpf path string true "Patient CPF"
// @Success     200 {object} contracts.PatientDTO
// @Failure     400 {object} fiber.Map
// @Failure     404 {object} fiber.Map
// @Router      /patients/{cpf} [get]
func (ctrl *PatientController) GetByCPF(c *fiber.Ctx) error {
	identifier := c.Params("cpf")
	if identifier == "" {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "cpf is required"})
	}

	result, err := ctrl.PatientService.FindByCPF(identifier)
	if err != nil {
		return c.Status(http.StatusNotFound).JSON(fiber.Map{"error": err.Error()})
	}

	return c.Status(http.StatusOK).JSON(result)
}

// ListPatients godoc
// @Summary     List all patients
// @Description Returns a paginated list of patients
// @Tags        Patients
// @Produce     json
// @Security    BearerAuth
// @Param       page  query int false "Page number (default 1)"
// @Param       limit query int false "Page size (default 20)"
// @Success     200  {array}  contracts.PatientDTO
// @Failure     500  {object} fiber.Map
// @Router      /patients [get]
func (ctrl *PatientController) ListPatients(c *fiber.Ctx) error {
	page  := c.QueryInt("page", 1)
	limit := c.QueryInt("limit", 20)
	if page < 1  { page = 1 }
	if limit < 1 { limit = 20 }

	results, err := ctrl.PatientService.List(page, limit)
	if err != nil {
		return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"error": "failed to retrieve patients"})
	}

	return c.Status(http.StatusOK).JSON(fiber.Map{
		"data":  results,
		"page":  page,
		"limit": limit,
	})
}
</go_file>


<go_file>
<go_version> go1.24
<go_pkg> main

// cmd/main.go — Fiber router setup
// Pattern: group-based routing + auth middleware + Swagger protection
// Observed in: Medical-App-Core/cmd/main.go
package main

import (
	"log"
	"os"

	"medical-sas-api/controllers"
	"medical-sas-api/initializers"
	_ "medical-sas-api/docs"

	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/basicauth"
	"github.com/gofiber/fiber/v2/middleware/cors"
	"github.com/gofiber/fiber/v2/middleware/logger"
	"github.com/gofiber/swagger"
	"github.com/joho/godotenv"
)

// bearerAuthMiddleware validates the Authorization: Bearer <token> header.
// Returns 401 if missing or invalid; calls Next() on success.
func bearerAuthMiddleware(svc *initializers.Services) fiber.Handler {
	return func(c *fiber.Ctx) error {
		header := c.Get("Authorization")
		if len(header) <= 7 || header[:7] != "Bearer " {
			return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
				"error": "missing or malformed Authorization header",
			})
		}
		if err := svc.AuthTokenService.ValidateToken(header[7:]); err != nil {
			return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
				"error":  "invalid or expired token",
				"reason": err.Error(),
			})
		}
		return c.Next()
	}
}

func configureMiddleware(app *fiber.App) {
	app.Use(cors.New(cors.Config{
		AllowOrigins: "*",
		AllowMethods: "GET,POST,PUT,PATCH,DELETE,OPTIONS",
		AllowHeaders: "Origin, Content-Type, Accept, Authorization",
	}))
	app.Use(logger.New(logger.Config{
		Format: `[$\{time\}] $\{status\} - $\{method\} $\{path\}\n`,
	}))
}

func registerRoutes(app *fiber.App, svc *initializers.Services) {
	auth := app.Group("/auth")
	auth.Post("/token",    controllers.NewAuthController(svc.AuthTokenService).GenerateToken)
	auth.Post("/validate", controllers.NewAuthController(svc.AuthTokenService).ValidateToken)

	protected := app.Group("/", bearerAuthMiddleware(svc))

	entityCtrl := controllers.NewPatientController(svc.PatientService)
	patients := protected.Group("/patients")
	patients.Post("/",              entityCtrl.CreatePatient)
	patients.Get("/",               entityCtrl.ListPatients)
	patients.Get("/:cpf",   entityCtrl.GetByCPF)
}

func main() {
	if err := godotenv.Load(); err != nil {
		log.Println("warning: .env file not found, using environment")
	}

	db  := initializers.InitialDB()
	initializers.RunMigrations(db)
	svc := initializers.InitServices(db)

	app := fiber.New(fiber.Config{AppName: "medical-sas-api v1"})
	configureMiddleware(app)

	// Swagger endpoint protected by basic auth
	swaggerUser := os.Getenv("SWAGGER_USER")
	swaggerPass := os.Getenv("SWAGGER_PASSWORD")
	if swaggerUser == "" || swaggerPass == "" {
		log.Fatal("SWAGGER_USER and SWAGGER_PASSWORD must be set")
	}
	swaggerAuth := basicauth.New(basicauth.Config{
		Users: map[string]string{swaggerUser: swaggerPass},
	})
	app.Get("/swagger/*", swaggerAuth, swagger.HandlerDefault)

	registerRoutes(app, svc)

	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}
	log.Printf("server listening on :%s", port)
	if err := app.Listen(":" + port); err != nil {
		log.Fatalf("server error: %v", err)
	}
}
</go_file>


<go_file>
<go_version> go1.24
<go_pkg> utils

// utils/responseUtil.go
// Pattern: response utility interface + JSON helper
// Observed in: Medical-App-Core/utils/responseUtil.go
package utils

import (
	"encoding/json"

	"github.com/gofiber/fiber/v2"
)

// ResponseUtil abstracts JSON response construction for testability.
type ResponseUtil interface {
	RespondWithJSON(c *fiber.Ctx, code int, payload any) error
	RespondWithError(c *fiber.Ctx, code int, message string) error
}

// JSONResponseUtil implements ResponseUtil using Fiber's context.
type JSONResponseUtil struct{}

func (ru *JSONResponseUtil) RespondWithJSON(c *fiber.Ctx, code int, payload any) error {
	body, err := json.Marshal(payload)
	if err != nil {
		return c.Status(fiber.StatusInternalServerError).
			JSON(fiber.Map{"error": "failed to marshal response"})
	}
	c.Set("Content-Type", "application/json")
	return c.Status(code).Send(body)
}

func (ru *JSONResponseUtil) RespondWithError(c *fiber.Ctx, code int, message string) error {
	return c.Status(code).JSON(fiber.Map{"error": message})
}
</go_file>


<go_file>
<go_version> go1.21
<go_pkg> controllers

// controllers/orderController.go
// Pattern: struct controller + constructor injection + Swagger annotations
// Observed in: Medical-App-Core/controllers/
package controllers

import (
	"net/http"
	"time"

	"ecommerce-api/services/contracts"
	"github.com/gofiber/fiber/v2"
)

// OrderController handles HTTP requests for the Order resource.
type OrderController struct {
	OrderService contracts.OrderServiceContract
}

// NewOrderController constructs a OrderController with its service dependency.
func NewOrderController(svc contracts.OrderServiceContract) *OrderController {
	return &OrderController{OrderService: svc}
}

// CreateOrder godoc
// @Summary     Create a new order
// @Description Create a new order in the system
// @Tags        Orders
// @Accept      json
// @Produce     json
// @Security    BearerAuth
// @Param       body body contracts.OrderInputDTO true "Order data"
// @Success     201  {object} fiber.Map
// @Failure     400  {object} fiber.Map
// @Failure     422  {object} fiber.Map
// @Failure     500  {object} fiber.Map
// @Router      /orders [post]
func (ctrl *OrderController) CreateOrder(c *fiber.Ctx) error {
	var input contracts.OrderInputDTO
	if err := c.BodyParser(&input); err != nil {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "invalid request payload"})
	}

	if input.CustomerID == "" {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "customer_id is required"})
	}
	if len(input.Items) == 0 {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "items cannot be empty"})
	}

	id, err := ctrl.OrderService.CreateFromInput(input)
	if err != nil {
		return c.Status(http.StatusUnprocessableEntity).JSON(fiber.Map{"error": err.Error()})
	}

	return c.Status(http.StatusCreated).JSON(fiber.Map{
		"message": "Order created successfully",
		"id":      id,
	})
}

// GetByOrderNumber godoc
// @Summary     Get order by OrderNumber
// @Description Retrieve a single order identified by its OrderNumber
// @Tags        Orders
// @Produce     json
// @Security    BearerAuth
// @Param       order_number path string true "Order OrderNumber"
// @Success     200 {object} contracts.OrderDTO
// @Failure     400 {object} fiber.Map
// @Failure     404 {object} fiber.Map
// @Router      /orders/{order_number} [get]
func (ctrl *OrderController) GetByOrderNumber(c *fiber.Ctx) error {
	identifier := c.Params("order_number")
	if identifier == "" {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "order_number is required"})
	}

	result, err := ctrl.OrderService.FindByOrderNumber(identifier)
	if err != nil {
		return c.Status(http.StatusNotFound).JSON(fiber.Map{"error": err.Error()})
	}

	return c.Status(http.StatusOK).JSON(result)
}

// ListOrders godoc
// @Summary     List all orders
// @Description Returns a paginated list of orders
// @Tags        Orders
// @Produce     json
// @Security    BearerAuth
// @Param       page  query int false "Page number (default 1)"
// @Param       limit query int false "Page size (default 20)"
// @Success     200  {array}  contracts.OrderDTO
// @Failure     500  {object} fiber.Map
// @Router      /orders [get]
func (ctrl *OrderController) ListOrders(c *fiber.Ctx) error {
	page  := c.QueryInt("page", 1)
	limit := c.QueryInt("limit", 20)
	if page < 1  { page = 1 }
	if limit < 1 { limit = 20 }

	results, err := ctrl.OrderService.List(page, limit)
	if err != nil {
		return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"error": "failed to retrieve orders"})
	}

	return c.Status(http.StatusOK).JSON(fiber.Map{
		"data":  results,
		"page":  page,
		"limit": limit,
	})
}
</go_file>


<go_file>
<go_version> go1.21
<go_pkg> main

// cmd/main.go — Fiber router setup
// Pattern: group-based routing + auth middleware + Swagger protection
// Observed in: Medical-App-Core/cmd/main.go
package main

import (
	"log"
	"os"

	"ecommerce-api/controllers"
	"ecommerce-api/initializers"
	_ "ecommerce-api/docs"

	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/basicauth"
	"github.com/gofiber/fiber/v2/middleware/cors"
	"github.com/gofiber/fiber/v2/middleware/logger"
	"github.com/gofiber/swagger"
	"github.com/joho/godotenv"
)

// bearerAuthMiddleware validates the Authorization: Bearer <token> header.
// Returns 401 if missing or invalid; calls Next() on success.
func bearerAuthMiddleware(svc *initializers.Services) fiber.Handler {
	return func(c *fiber.Ctx) error {
		header := c.Get("Authorization")
		if len(header) <= 7 || header[:7] != "Bearer " {
			return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
				"error": "missing or malformed Authorization header",
			})
		}
		if err := svc.AuthTokenService.ValidateToken(header[7:]); err != nil {
			return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
				"error":  "invalid or expired token",
				"reason": err.Error(),
			})
		}
		return c.Next()
	}
}

func configureMiddleware(app *fiber.App) {
	app.Use(cors.New(cors.Config{
		AllowOrigins: "*",
		AllowMethods: "GET,POST,PUT,PATCH,DELETE,OPTIONS",
		AllowHeaders: "Origin, Content-Type, Accept, Authorization",
	}))
	app.Use(logger.New(logger.Config{
		Format: `[$\{time\}] $\{status\} - $\{method\} $\{path\}\n`,
	}))
}

func registerRoutes(app *fiber.App, svc *initializers.Services) {
	auth := app.Group("/auth")
	auth.Post("/token",    controllers.NewAuthController(svc.AuthTokenService).GenerateToken)
	auth.Post("/validate", controllers.NewAuthController(svc.AuthTokenService).ValidateToken)

	protected := app.Group("/", bearerAuthMiddleware(svc))

	entityCtrl := controllers.NewOrderController(svc.OrderService)
	orders := protected.Group("/orders")
	orders.Post("/",              entityCtrl.CreateOrder)
	orders.Get("/",               entityCtrl.ListOrders)
	orders.Get("/:order_number",   entityCtrl.GetByOrderNumber)
}

func main() {
	if err := godotenv.Load(); err != nil {
		log.Println("warning: .env file not found, using environment")
	}

	db  := initializers.InitialDB()
	initializers.RunMigrations(db)
	svc := initializers.InitServices(db)

	app := fiber.New(fiber.Config{AppName: "ecommerce-api v1"})
	configureMiddleware(app)

	// Swagger endpoint protected by basic auth
	swaggerUser := os.Getenv("SWAGGER_USER")
	swaggerPass := os.Getenv("SWAGGER_PASSWORD")
	if swaggerUser == "" || swaggerPass == "" {
		log.Fatal("SWAGGER_USER and SWAGGER_PASSWORD must be set")
	}
	swaggerAuth := basicauth.New(basicauth.Config{
		Users: map[string]string{swaggerUser: swaggerPass},
	})
	app.Get("/swagger/*", swaggerAuth, swagger.HandlerDefault)

	registerRoutes(app, svc)

	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}
	log.Printf("server listening on :%s", port)
	if err := app.Listen(":" + port); err != nil {
		log.Fatalf("server error: %v", err)
	}
}
</go_file>


<go_file>
<go_version> go1.22
<go_pkg> controllers

// controllers/orderController.go
// Pattern: struct controller + constructor injection + Swagger annotations
// Observed in: Medical-App-Core/controllers/
package controllers

import (
	"net/http"
	"time"

	"ecommerce-api/services/contracts"
	"github.com/gofiber/fiber/v2"
)

// OrderController handles HTTP requests for the Order resource.
type OrderController struct {
	OrderService contracts.OrderServiceContract
}

// NewOrderController constructs a OrderController with its service dependency.
func NewOrderController(svc contracts.OrderServiceContract) *OrderController {
	return &OrderController{OrderService: svc}
}

// CreateOrder godoc
// @Summary     Create a new order
// @Description Create a new order in the system
// @Tags        Orders
// @Accept      json
// @Produce     json
// @Security    BearerAuth
// @Param       body body contracts.OrderInputDTO true "Order data"
// @Success     201  {object} fiber.Map
// @Failure     400  {object} fiber.Map
// @Failure     422  {object} fiber.Map
// @Failure     500  {object} fiber.Map
// @Router      /orders [post]
func (ctrl *OrderController) CreateOrder(c *fiber.Ctx) error {
	var input contracts.OrderInputDTO
	if err := c.BodyParser(&input); err != nil {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "invalid request payload"})
	}

	if input.CustomerID == "" {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "customer_id is required"})
	}
	if len(input.Items) == 0 {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "items cannot be empty"})
	}

	id, err := ctrl.OrderService.CreateFromInput(input)
	if err != nil {
		return c.Status(http.StatusUnprocessableEntity).JSON(fiber.Map{"error": err.Error()})
	}

	return c.Status(http.StatusCreated).JSON(fiber.Map{
		"message": "Order created successfully",
		"id":      id,
	})
}

// GetByOrderNumber godoc
// @Summary     Get order by OrderNumber
// @Description Retrieve a single order identified by its OrderNumber
// @Tags        Orders
// @Produce     json
// @Security    BearerAuth
// @Param       order_number path string true "Order OrderNumber"
// @Success     200 {object} contracts.OrderDTO
// @Failure     400 {object} fiber.Map
// @Failure     404 {object} fiber.Map
// @Router      /orders/{order_number} [get]
func (ctrl *OrderController) GetByOrderNumber(c *fiber.Ctx) error {
	identifier := c.Params("order_number")
	if identifier == "" {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "order_number is required"})
	}

	result, err := ctrl.OrderService.FindByOrderNumber(identifier)
	if err != nil {
		return c.Status(http.StatusNotFound).JSON(fiber.Map{"error": err.Error()})
	}

	return c.Status(http.StatusOK).JSON(result)
}

// ListOrders godoc
// @Summary     List all orders
// @Description Returns a paginated list of orders
// @Tags        Orders
// @Produce     json
// @Security    BearerAuth
// @Param       page  query int false "Page number (default 1)"
// @Param       limit query int false "Page size (default 20)"
// @Success     200  {array}  contracts.OrderDTO
// @Failure     500  {object} fiber.Map
// @Router      /orders [get]
func (ctrl *OrderController) ListOrders(c *fiber.Ctx) error {
	page  := c.QueryInt("page", 1)
	limit := c.QueryInt("limit", 20)
	if page < 1  { page = 1 }
	if limit < 1 { limit = 20 }

	results, err := ctrl.OrderService.List(page, limit)
	if err != nil {
		return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"error": "failed to retrieve orders"})
	}

	return c.Status(http.StatusOK).JSON(fiber.Map{
		"data":  results,
		"page":  page,
		"limit": limit,
	})
}
</go_file>


<go_file>
<go_version> go1.22
<go_pkg> main

// cmd/main.go — Fiber router setup
// Pattern: group-based routing + auth middleware + Swagger protection
// Observed in: Medical-App-Core/cmd/main.go
package main

import (
	"log"
	"os"

	"ecommerce-api/controllers"
	"ecommerce-api/initializers"
	_ "ecommerce-api/docs"

	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/basicauth"
	"github.com/gofiber/fiber/v2/middleware/cors"
	"github.com/gofiber/fiber/v2/middleware/logger"
	"github.com/gofiber/swagger"
	"github.com/joho/godotenv"
)

// bearerAuthMiddleware validates the Authorization: Bearer <token> header.
// Returns 401 if missing or invalid; calls Next() on success.
func bearerAuthMiddleware(svc *initializers.Services) fiber.Handler {
	return func(c *fiber.Ctx) error {
		header := c.Get("Authorization")
		if len(header) <= 7 || header[:7] != "Bearer " {
			return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
				"error": "missing or malformed Authorization header",
			})
		}
		if err := svc.AuthTokenService.ValidateToken(header[7:]); err != nil {
			return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
				"error":  "invalid or expired token",
				"reason": err.Error(),
			})
		}
		return c.Next()
	}
}

func configureMiddleware(app *fiber.App) {
	app.Use(cors.New(cors.Config{
		AllowOrigins: "*",
		AllowMethods: "GET,POST,PUT,PATCH,DELETE,OPTIONS",
		AllowHeaders: "Origin, Content-Type, Accept, Authorization",
	}))
	app.Use(logger.New(logger.Config{
		Format: `[$\{time\}] $\{status\} - $\{method\} $\{path\}\n`,
	}))
}

func registerRoutes(app *fiber.App, svc *initializers.Services) {
	auth := app.Group("/auth")
	auth.Post("/token",    controllers.NewAuthController(svc.AuthTokenService).GenerateToken)
	auth.Post("/validate", controllers.NewAuthController(svc.AuthTokenService).ValidateToken)

	protected := app.Group("/", bearerAuthMiddleware(svc))

	entityCtrl := controllers.NewOrderController(svc.OrderService)
	orders := protected.Group("/orders")
	orders.Post("/",              entityCtrl.CreateOrder)
	orders.Get("/",               entityCtrl.ListOrders)
	orders.Get("/:order_number",   entityCtrl.GetByOrderNumber)
}

func main() {
	if err := godotenv.Load(); err != nil {
		log.Println("warning: .env file not found, using environment")
	}

	db  := initializers.InitialDB()
	initializers.RunMigrations(db)
	svc := initializers.InitServices(db)

	app := fiber.New(fiber.Config{AppName: "ecommerce-api v1"})
	configureMiddleware(app)

	// Swagger endpoint protected by basic auth
	swaggerUser := os.Getenv("SWAGGER_USER")
	swaggerPass := os.Getenv("SWAGGER_PASSWORD")
	if swaggerUser == "" || swaggerPass == "" {
		log.Fatal("SWAGGER_USER and SWAGGER_PASSWORD must be set")
	}
	swaggerAuth := basicauth.New(basicauth.Config{
		Users: map[string]string{swaggerUser: swaggerPass},
	})
	app.Get("/swagger/*", swaggerAuth, swagger.HandlerDefault)

	registerRoutes(app, svc)

	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}
	log.Printf("server listening on :%s", port)
	if err := app.Listen(":" + port); err != nil {
		log.Fatalf("server error: %v", err)
	}
}
</go_file>


<go_file>
<go_version> go1.23
<go_pkg> controllers

// controllers/orderController.go
// Pattern: struct controller + constructor injection + Swagger annotations
// Observed in: Medical-App-Core/controllers/
package controllers

import (
	"net/http"
	"time"

	"ecommerce-api/services/contracts"
	"github.com/gofiber/fiber/v2"
)

// OrderController handles HTTP requests for the Order resource.
type OrderController struct {
	OrderService contracts.OrderServiceContract
}

// NewOrderController constructs a OrderController with its service dependency.
func NewOrderController(svc contracts.OrderServiceContract) *OrderController {
	return &OrderController{OrderService: svc}
}

// CreateOrder godoc
// @Summary     Create a new order
// @Description Create a new order in the system
// @Tags        Orders
// @Accept      json
// @Produce     json
// @Security    BearerAuth
// @Param       body body contracts.OrderInputDTO true "Order data"
// @Success     201  {object} fiber.Map
// @Failure     400  {object} fiber.Map
// @Failure     422  {object} fiber.Map
// @Failure     500  {object} fiber.Map
// @Router      /orders [post]
func (ctrl *OrderController) CreateOrder(c *fiber.Ctx) error {
	var input contracts.OrderInputDTO
	if err := c.BodyParser(&input); err != nil {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "invalid request payload"})
	}

	if input.CustomerID == "" {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "customer_id is required"})
	}
	if len(input.Items) == 0 {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "items cannot be empty"})
	}

	id, err := ctrl.OrderService.CreateFromInput(input)
	if err != nil {
		return c.Status(http.StatusUnprocessableEntity).JSON(fiber.Map{"error": err.Error()})
	}

	return c.Status(http.StatusCreated).JSON(fiber.Map{
		"message": "Order created successfully",
		"id":      id,
	})
}

// GetByOrderNumber godoc
// @Summary     Get order by OrderNumber
// @Description Retrieve a single order identified by its OrderNumber
// @Tags        Orders
// @Produce     json
// @Security    BearerAuth
// @Param       order_number path string true "Order OrderNumber"
// @Success     200 {object} contracts.OrderDTO
// @Failure     400 {object} fiber.Map
// @Failure     404 {object} fiber.Map
// @Router      /orders/{order_number} [get]
func (ctrl *OrderController) GetByOrderNumber(c *fiber.Ctx) error {
	identifier := c.Params("order_number")
	if identifier == "" {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "order_number is required"})
	}

	result, err := ctrl.OrderService.FindByOrderNumber(identifier)
	if err != nil {
		return c.Status(http.StatusNotFound).JSON(fiber.Map{"error": err.Error()})
	}

	return c.Status(http.StatusOK).JSON(result)
}

// ListOrders godoc
// @Summary     List all orders
// @Description Returns a paginated list of orders
// @Tags        Orders
// @Produce     json
// @Security    BearerAuth
// @Param       page  query int false "Page number (default 1)"
// @Param       limit query int false "Page size (default 20)"
// @Success     200  {array}  contracts.OrderDTO
// @Failure     500  {object} fiber.Map
// @Router      /orders [get]
func (ctrl *OrderController) ListOrders(c *fiber.Ctx) error {
	page  := c.QueryInt("page", 1)
	limit := c.QueryInt("limit", 20)
	if page < 1  { page = 1 }
	if limit < 1 { limit = 20 }

	results, err := ctrl.OrderService.List(page, limit)
	if err != nil {
		return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"error": "failed to retrieve orders"})
	}

	return c.Status(http.StatusOK).JSON(fiber.Map{
		"data":  results,
		"page":  page,
		"limit": limit,
	})
}
</go_file>


<go_file>
<go_version> go1.23
<go_pkg> main

// cmd/main.go — Fiber router setup
// Pattern: group-based routing + auth middleware + Swagger protection
// Observed in: Medical-App-Core/cmd/main.go
package main

import (
	"log"
	"os"

	"ecommerce-api/controllers"
	"ecommerce-api/initializers"
	_ "ecommerce-api/docs"

	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/basicauth"
	"github.com/gofiber/fiber/v2/middleware/cors"
	"github.com/gofiber/fiber/v2/middleware/logger"
	"github.com/gofiber/swagger"
	"github.com/joho/godotenv"
)

// bearerAuthMiddleware validates the Authorization: Bearer <token> header.
// Returns 401 if missing or invalid; calls Next() on success.
func bearerAuthMiddleware(svc *initializers.Services) fiber.Handler {
	return func(c *fiber.Ctx) error {
		header := c.Get("Authorization")
		if len(header) <= 7 || header[:7] != "Bearer " {
			return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
				"error": "missing or malformed Authorization header",
			})
		}
		if err := svc.AuthTokenService.ValidateToken(header[7:]); err != nil {
			return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
				"error":  "invalid or expired token",
				"reason": err.Error(),
			})
		}
		return c.Next()
	}
}

func configureMiddleware(app *fiber.App) {
	app.Use(cors.New(cors.Config{
		AllowOrigins: "*",
		AllowMethods: "GET,POST,PUT,PATCH,DELETE,OPTIONS",
		AllowHeaders: "Origin, Content-Type, Accept, Authorization",
	}))
	app.Use(logger.New(logger.Config{
		Format: `[$\{time\}] $\{status\} - $\{method\} $\{path\}\n`,
	}))
}

func registerRoutes(app *fiber.App, svc *initializers.Services) {
	auth := app.Group("/auth")
	auth.Post("/token",    controllers.NewAuthController(svc.AuthTokenService).GenerateToken)
	auth.Post("/validate", controllers.NewAuthController(svc.AuthTokenService).ValidateToken)

	protected := app.Group("/", bearerAuthMiddleware(svc))

	entityCtrl := controllers.NewOrderController(svc.OrderService)
	orders := protected.Group("/orders")
	orders.Post("/",              entityCtrl.CreateOrder)
	orders.Get("/",               entityCtrl.ListOrders)
	orders.Get("/:order_number",   entityCtrl.GetByOrderNumber)
}

func main() {
	if err := godotenv.Load(); err != nil {
		log.Println("warning: .env file not found, using environment")
	}

	db  := initializers.InitialDB()
	initializers.RunMigrations(db)
	svc := initializers.InitServices(db)

	app := fiber.New(fiber.Config{AppName: "ecommerce-api v1"})
	configureMiddleware(app)

	// Swagger endpoint protected by basic auth
	swaggerUser := os.Getenv("SWAGGER_USER")
	swaggerPass := os.Getenv("SWAGGER_PASSWORD")
	if swaggerUser == "" || swaggerPass == "" {
		log.Fatal("SWAGGER_USER and SWAGGER_PASSWORD must be set")
	}
	swaggerAuth := basicauth.New(basicauth.Config{
		Users: map[string]string{swaggerUser: swaggerPass},
	})
	app.Get("/swagger/*", swaggerAuth, swagger.HandlerDefault)

	registerRoutes(app, svc)

	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}
	log.Printf("server listening on :%s", port)
	if err := app.Listen(":" + port); err != nil {
		log.Fatalf("server error: %v", err)
	}
}
</go_file>


<go_file>
<go_version> go1.24
<go_pkg> controllers

// controllers/orderController.go
// Pattern: struct controller + constructor injection + Swagger annotations
// Observed in: Medical-App-Core/controllers/
package controllers

import (
	"net/http"
	"time"

	"ecommerce-api/services/contracts"
	"github.com/gofiber/fiber/v2"
)

// OrderController handles HTTP requests for the Order resource.
type OrderController struct {
	OrderService contracts.OrderServiceContract
}

// NewOrderController constructs a OrderController with its service dependency.
func NewOrderController(svc contracts.OrderServiceContract) *OrderController {
	return &OrderController{OrderService: svc}
}

// CreateOrder godoc
// @Summary     Create a new order
// @Description Create a new order in the system
// @Tags        Orders
// @Accept      json
// @Produce     json
// @Security    BearerAuth
// @Param       body body contracts.OrderInputDTO true "Order data"
// @Success     201  {object} fiber.Map
// @Failure     400  {object} fiber.Map
// @Failure     422  {object} fiber.Map
// @Failure     500  {object} fiber.Map
// @Router      /orders [post]
func (ctrl *OrderController) CreateOrder(c *fiber.Ctx) error {
	var input contracts.OrderInputDTO
	if err := c.BodyParser(&input); err != nil {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "invalid request payload"})
	}

	if input.CustomerID == "" {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "customer_id is required"})
	}
	if len(input.Items) == 0 {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "items cannot be empty"})
	}

	id, err := ctrl.OrderService.CreateFromInput(input)
	if err != nil {
		return c.Status(http.StatusUnprocessableEntity).JSON(fiber.Map{"error": err.Error()})
	}

	return c.Status(http.StatusCreated).JSON(fiber.Map{
		"message": "Order created successfully",
		"id":      id,
	})
}

// GetByOrderNumber godoc
// @Summary     Get order by OrderNumber
// @Description Retrieve a single order identified by its OrderNumber
// @Tags        Orders
// @Produce     json
// @Security    BearerAuth
// @Param       order_number path string true "Order OrderNumber"
// @Success     200 {object} contracts.OrderDTO
// @Failure     400 {object} fiber.Map
// @Failure     404 {object} fiber.Map
// @Router      /orders/{order_number} [get]
func (ctrl *OrderController) GetByOrderNumber(c *fiber.Ctx) error {
	identifier := c.Params("order_number")
	if identifier == "" {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "order_number is required"})
	}

	result, err := ctrl.OrderService.FindByOrderNumber(identifier)
	if err != nil {
		return c.Status(http.StatusNotFound).JSON(fiber.Map{"error": err.Error()})
	}

	return c.Status(http.StatusOK).JSON(result)
}

// ListOrders godoc
// @Summary     List all orders
// @Description Returns a paginated list of orders
// @Tags        Orders
// @Produce     json
// @Security    BearerAuth
// @Param       page  query int false "Page number (default 1)"
// @Param       limit query int false "Page size (default 20)"
// @Success     200  {array}  contracts.OrderDTO
// @Failure     500  {object} fiber.Map
// @Router      /orders [get]
func (ctrl *OrderController) ListOrders(c *fiber.Ctx) error {
	page  := c.QueryInt("page", 1)
	limit := c.QueryInt("limit", 20)
	if page < 1  { page = 1 }
	if limit < 1 { limit = 20 }

	results, err := ctrl.OrderService.List(page, limit)
	if err != nil {
		return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"error": "failed to retrieve orders"})
	}

	return c.Status(http.StatusOK).JSON(fiber.Map{
		"data":  results,
		"page":  page,
		"limit": limit,
	})
}
</go_file>


<go_file>
<go_version> go1.24
<go_pkg> main

// cmd/main.go — Fiber router setup
// Pattern: group-based routing + auth middleware + Swagger protection
// Observed in: Medical-App-Core/cmd/main.go
package main

import (
	"log"
	"os"

	"ecommerce-api/controllers"
	"ecommerce-api/initializers"
	_ "ecommerce-api/docs"

	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/basicauth"
	"github.com/gofiber/fiber/v2/middleware/cors"
	"github.com/gofiber/fiber/v2/middleware/logger"
	"github.com/gofiber/swagger"
	"github.com/joho/godotenv"
)

// bearerAuthMiddleware validates the Authorization: Bearer <token> header.
// Returns 401 if missing or invalid; calls Next() on success.
func bearerAuthMiddleware(svc *initializers.Services) fiber.Handler {
	return func(c *fiber.Ctx) error {
		header := c.Get("Authorization")
		if len(header) <= 7 || header[:7] != "Bearer " {
			return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
				"error": "missing or malformed Authorization header",
			})
		}
		if err := svc.AuthTokenService.ValidateToken(header[7:]); err != nil {
			return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
				"error":  "invalid or expired token",
				"reason": err.Error(),
			})
		}
		return c.Next()
	}
}

func configureMiddleware(app *fiber.App) {
	app.Use(cors.New(cors.Config{
		AllowOrigins: "*",
		AllowMethods: "GET,POST,PUT,PATCH,DELETE,OPTIONS",
		AllowHeaders: "Origin, Content-Type, Accept, Authorization",
	}))
	app.Use(logger.New(logger.Config{
		Format: `[$\{time\}] $\{status\} - $\{method\} $\{path\}\n`,
	}))
}

func registerRoutes(app *fiber.App, svc *initializers.Services) {
	auth := app.Group("/auth")
	auth.Post("/token",    controllers.NewAuthController(svc.AuthTokenService).GenerateToken)
	auth.Post("/validate", controllers.NewAuthController(svc.AuthTokenService).ValidateToken)

	protected := app.Group("/", bearerAuthMiddleware(svc))

	entityCtrl := controllers.NewOrderController(svc.OrderService)
	orders := protected.Group("/orders")
	orders.Post("/",              entityCtrl.CreateOrder)
	orders.Get("/",               entityCtrl.ListOrders)
	orders.Get("/:order_number",   entityCtrl.GetByOrderNumber)
}

func main() {
	if err := godotenv.Load(); err != nil {
		log.Println("warning: .env file not found, using environment")
	}

	db  := initializers.InitialDB()
	initializers.RunMigrations(db)
	svc := initializers.InitServices(db)

	app := fiber.New(fiber.Config{AppName: "ecommerce-api v1"})
	configureMiddleware(app)

	// Swagger endpoint protected by basic auth
	swaggerUser := os.Getenv("SWAGGER_USER")
	swaggerPass := os.Getenv("SWAGGER_PASSWORD")
	if swaggerUser == "" || swaggerPass == "" {
		log.Fatal("SWAGGER_USER and SWAGGER_PASSWORD must be set")
	}
	swaggerAuth := basicauth.New(basicauth.Config{
		Users: map[string]string{swaggerUser: swaggerPass},
	})
	app.Get("/swagger/*", swaggerAuth, swagger.HandlerDefault)

	registerRoutes(app, svc)

	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}
	log.Printf("server listening on :%s", port)
	if err := app.Listen(":" + port); err != nil {
		log.Fatalf("server error: %v", err)
	}
}
</go_file>


<go_file>
<go_version> go1.21
<go_pkg> controllers

// controllers/employeeController.go
// Pattern: struct controller + constructor injection + Swagger annotations
// Observed in: Medical-App-Core/controllers/
package controllers

import (
	"net/http"
	"time"

	"hrm-api/services/contracts"
	"github.com/gofiber/fiber/v2"
)

// EmployeeController handles HTTP requests for the Employee resource.
type EmployeeController struct {
	EmployeeService contracts.EmployeeServiceContract
}

// NewEmployeeController constructs a EmployeeController with its service dependency.
func NewEmployeeController(svc contracts.EmployeeServiceContract) *EmployeeController {
	return &EmployeeController{EmployeeService: svc}
}

// CreateEmployee godoc
// @Summary     Create a new employee
// @Description Create a new employee in the system
// @Tags        Employees
// @Accept      json
// @Produce     json
// @Security    BearerAuth
// @Param       body body contracts.EmployeeInputDTO true "Employee data"
// @Success     201  {object} fiber.Map
// @Failure     400  {object} fiber.Map
// @Failure     422  {object} fiber.Map
// @Failure     500  {object} fiber.Map
// @Router      /employees [post]
func (ctrl *EmployeeController) CreateEmployee(c *fiber.Ctx) error {
	var input contracts.EmployeeInputDTO
	if err := c.BodyParser(&input); err != nil {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "invalid request payload"})
	}

	if input.DepartmentName == "" {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "department_name is required"})
	}
	if input.Position == "" {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "position is required"})
	}

	id, err := ctrl.EmployeeService.CreateFromInput(input)
	if err != nil {
		return c.Status(http.StatusUnprocessableEntity).JSON(fiber.Map{"error": err.Error()})
	}

	return c.Status(http.StatusCreated).JSON(fiber.Map{
		"message": "Employee created successfully",
		"id":      id,
	})
}

// GetByCPF godoc
// @Summary     Get employee by CPF
// @Description Retrieve a single employee identified by its CPF
// @Tags        Employees
// @Produce     json
// @Security    BearerAuth
// @Param       cpf path string true "Employee CPF"
// @Success     200 {object} contracts.EmployeeDTO
// @Failure     400 {object} fiber.Map
// @Failure     404 {object} fiber.Map
// @Router      /employees/{cpf} [get]
func (ctrl *EmployeeController) GetByCPF(c *fiber.Ctx) error {
	identifier := c.Params("cpf")
	if identifier == "" {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "cpf is required"})
	}

	result, err := ctrl.EmployeeService.FindByCPF(identifier)
	if err != nil {
		return c.Status(http.StatusNotFound).JSON(fiber.Map{"error": err.Error()})
	}

	return c.Status(http.StatusOK).JSON(result)
}

// ListEmployees godoc
// @Summary     List all employees
// @Description Returns a paginated list of employees
// @Tags        Employees
// @Produce     json
// @Security    BearerAuth
// @Param       page  query int false "Page number (default 1)"
// @Param       limit query int false "Page size (default 20)"
// @Success     200  {array}  contracts.EmployeeDTO
// @Failure     500  {object} fiber.Map
// @Router      /employees [get]
func (ctrl *EmployeeController) ListEmployees(c *fiber.Ctx) error {
	page  := c.QueryInt("page", 1)
	limit := c.QueryInt("limit", 20)
	if page < 1  { page = 1 }
	if limit < 1 { limit = 20 }

	results, err := ctrl.EmployeeService.List(page, limit)
	if err != nil {
		return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"error": "failed to retrieve employees"})
	}

	return c.Status(http.StatusOK).JSON(fiber.Map{
		"data":  results,
		"page":  page,
		"limit": limit,
	})
}
</go_file>


<go_file>
<go_version> go1.21
<go_pkg> main

// cmd/main.go — Fiber router setup
// Pattern: group-based routing + auth middleware + Swagger protection
// Observed in: Medical-App-Core/cmd/main.go
package main

import (
	"log"
	"os"

	"hrm-api/controllers"
	"hrm-api/initializers"
	_ "hrm-api/docs"

	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/basicauth"
	"github.com/gofiber/fiber/v2/middleware/cors"
	"github.com/gofiber/fiber/v2/middleware/logger"
	"github.com/gofiber/swagger"
	"github.com/joho/godotenv"
)

// bearerAuthMiddleware validates the Authorization: Bearer <token> header.
// Returns 401 if missing or invalid; calls Next() on success.
func bearerAuthMiddleware(svc *initializers.Services) fiber.Handler {
	return func(c *fiber.Ctx) error {
		header := c.Get("Authorization")
		if len(header) <= 7 || header[:7] != "Bearer " {
			return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
				"error": "missing or malformed Authorization header",
			})
		}
		if err := svc.AuthTokenService.ValidateToken(header[7:]); err != nil {
			return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
				"error":  "invalid or expired token",
				"reason": err.Error(),
			})
		}
		return c.Next()
	}
}

func configureMiddleware(app *fiber.App) {
	app.Use(cors.New(cors.Config{
		AllowOrigins: "*",
		AllowMethods: "GET,POST,PUT,PATCH,DELETE,OPTIONS",
		AllowHeaders: "Origin, Content-Type, Accept, Authorization",
	}))
	app.Use(logger.New(logger.Config{
		Format: `[$\{time\}] $\{status\} - $\{method\} $\{path\}\n`,
	}))
}

func registerRoutes(app *fiber.App, svc *initializers.Services) {
	auth := app.Group("/auth")
	auth.Post("/token",    controllers.NewAuthController(svc.AuthTokenService).GenerateToken)
	auth.Post("/validate", controllers.NewAuthController(svc.AuthTokenService).ValidateToken)

	protected := app.Group("/", bearerAuthMiddleware(svc))

	entityCtrl := controllers.NewEmployeeController(svc.EmployeeService)
	employees := protected.Group("/employees")
	employees.Post("/",              entityCtrl.CreateEmployee)
	employees.Get("/",               entityCtrl.ListEmployees)
	employees.Get("/:cpf",   entityCtrl.GetByCPF)
}

func main() {
	if err := godotenv.Load(); err != nil {
		log.Println("warning: .env file not found, using environment")
	}

	db  := initializers.InitialDB()
	initializers.RunMigrations(db)
	svc := initializers.InitServices(db)

	app := fiber.New(fiber.Config{AppName: "hrm-api v1"})
	configureMiddleware(app)

	// Swagger endpoint protected by basic auth
	swaggerUser := os.Getenv("SWAGGER_USER")
	swaggerPass := os.Getenv("SWAGGER_PASSWORD")
	if swaggerUser == "" || swaggerPass == "" {
		log.Fatal("SWAGGER_USER and SWAGGER_PASSWORD must be set")
	}
	swaggerAuth := basicauth.New(basicauth.Config{
		Users: map[string]string{swaggerUser: swaggerPass},
	})
	app.Get("/swagger/*", swaggerAuth, swagger.HandlerDefault)

	registerRoutes(app, svc)

	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}
	log.Printf("server listening on :%s", port)
	if err := app.Listen(":" + port); err != nil {
		log.Fatalf("server error: %v", err)
	}
}
</go_file>


<go_file>
<go_version> go1.22
<go_pkg> controllers

// controllers/employeeController.go
// Pattern: struct controller + constructor injection + Swagger annotations
// Observed in: Medical-App-Core/controllers/
package controllers

import (
	"net/http"
	"time"

	"hrm-api/services/contracts"
	"github.com/gofiber/fiber/v2"
)

// EmployeeController handles HTTP requests for the Employee resource.
type EmployeeController struct {
	EmployeeService contracts.EmployeeServiceContract
}

// NewEmployeeController constructs a EmployeeController with its service dependency.
func NewEmployeeController(svc contracts.EmployeeServiceContract) *EmployeeController {
	return &EmployeeController{EmployeeService: svc}
}

// CreateEmployee godoc
// @Summary     Create a new employee
// @Description Create a new employee in the system
// @Tags        Employees
// @Accept      json
// @Produce     json
// @Security    BearerAuth
// @Param       body body contracts.EmployeeInputDTO true "Employee data"
// @Success     201  {object} fiber.Map
// @Failure     400  {object} fiber.Map
// @Failure     422  {object} fiber.Map
// @Failure     500  {object} fiber.Map
// @Router      /employees [post]
func (ctrl *EmployeeController) CreateEmployee(c *fiber.Ctx) error {
	var input contracts.EmployeeInputDTO
	if err := c.BodyParser(&input); err != nil {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "invalid request payload"})
	}

	if input.DepartmentName == "" {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "department_name is required"})
	}
	if input.Position == "" {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "position is required"})
	}

	id, err := ctrl.EmployeeService.CreateFromInput(input)
	if err != nil {
		return c.Status(http.StatusUnprocessableEntity).JSON(fiber.Map{"error": err.Error()})
	}

	return c.Status(http.StatusCreated).JSON(fiber.Map{
		"message": "Employee created successfully",
		"id":      id,
	})
}

// GetByCPF godoc
// @Summary     Get employee by CPF
// @Description Retrieve a single employee identified by its CPF
// @Tags        Employees
// @Produce     json
// @Security    BearerAuth
// @Param       cpf path string true "Employee CPF"
// @Success     200 {object} contracts.EmployeeDTO
// @Failure     400 {object} fiber.Map
// @Failure     404 {object} fiber.Map
// @Router      /employees/{cpf} [get]
func (ctrl *EmployeeController) GetByCPF(c *fiber.Ctx) error {
	identifier := c.Params("cpf")
	if identifier == "" {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "cpf is required"})
	}

	result, err := ctrl.EmployeeService.FindByCPF(identifier)
	if err != nil {
		return c.Status(http.StatusNotFound).JSON(fiber.Map{"error": err.Error()})
	}

	return c.Status(http.StatusOK).JSON(result)
}

// ListEmployees godoc
// @Summary     List all employees
// @Description Returns a paginated list of employees
// @Tags        Employees
// @Produce     json
// @Security    BearerAuth
// @Param       page  query int false "Page number (default 1)"
// @Param       limit query int false "Page size (default 20)"
// @Success     200  {array}  contracts.EmployeeDTO
// @Failure     500  {object} fiber.Map
// @Router      /employees [get]
func (ctrl *EmployeeController) ListEmployees(c *fiber.Ctx) error {
	page  := c.QueryInt("page", 1)
	limit := c.QueryInt("limit", 20)
	if page < 1  { page = 1 }
	if limit < 1 { limit = 20 }

	results, err := ctrl.EmployeeService.List(page, limit)
	if err != nil {
		return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"error": "failed to retrieve employees"})
	}

	return c.Status(http.StatusOK).JSON(fiber.Map{
		"data":  results,
		"page":  page,
		"limit": limit,
	})
}
</go_file>


<go_file>
<go_version> go1.22
<go_pkg> main

// cmd/main.go — Fiber router setup
// Pattern: group-based routing + auth middleware + Swagger protection
// Observed in: Medical-App-Core/cmd/main.go
package main

import (
	"log"
	"os"

	"hrm-api/controllers"
	"hrm-api/initializers"
	_ "hrm-api/docs"

	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/basicauth"
	"github.com/gofiber/fiber/v2/middleware/cors"
	"github.com/gofiber/fiber/v2/middleware/logger"
	"github.com/gofiber/swagger"
	"github.com/joho/godotenv"
)

// bearerAuthMiddleware validates the Authorization: Bearer <token> header.
// Returns 401 if missing or invalid; calls Next() on success.
func bearerAuthMiddleware(svc *initializers.Services) fiber.Handler {
	return func(c *fiber.Ctx) error {
		header := c.Get("Authorization")
		if len(header) <= 7 || header[:7] != "Bearer " {
			return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
				"error": "missing or malformed Authorization header",
			})
		}
		if err := svc.AuthTokenService.ValidateToken(header[7:]); err != nil {
			return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
				"error":  "invalid or expired token",
				"reason": err.Error(),
			})
		}
		return c.Next()
	}
}

func configureMiddleware(app *fiber.App) {
	app.Use(cors.New(cors.Config{
		AllowOrigins: "*",
		AllowMethods: "GET,POST,PUT,PATCH,DELETE,OPTIONS",
		AllowHeaders: "Origin, Content-Type, Accept, Authorization",
	}))
	app.Use(logger.New(logger.Config{
		Format: `[$\{time\}] $\{status\} - $\{method\} $\{path\}\n`,
	}))
}

func registerRoutes(app *fiber.App, svc *initializers.Services) {
	auth := app.Group("/auth")
	auth.Post("/token",    controllers.NewAuthController(svc.AuthTokenService).GenerateToken)
	auth.Post("/validate", controllers.NewAuthController(svc.AuthTokenService).ValidateToken)

	protected := app.Group("/", bearerAuthMiddleware(svc))

	entityCtrl := controllers.NewEmployeeController(svc.EmployeeService)
	employees := protected.Group("/employees")
	employees.Post("/",              entityCtrl.CreateEmployee)
	employees.Get("/",               entityCtrl.ListEmployees)
	employees.Get("/:cpf",   entityCtrl.GetByCPF)
}

func main() {
	if err := godotenv.Load(); err != nil {
		log.Println("warning: .env file not found, using environment")
	}

	db  := initializers.InitialDB()
	initializers.RunMigrations(db)
	svc := initializers.InitServices(db)

	app := fiber.New(fiber.Config{AppName: "hrm-api v1"})
	configureMiddleware(app)

	// Swagger endpoint protected by basic auth
	swaggerUser := os.Getenv("SWAGGER_USER")
	swaggerPass := os.Getenv("SWAGGER_PASSWORD")
	if swaggerUser == "" || swaggerPass == "" {
		log.Fatal("SWAGGER_USER and SWAGGER_PASSWORD must be set")
	}
	swaggerAuth := basicauth.New(basicauth.Config{
		Users: map[string]string{swaggerUser: swaggerPass},
	})
	app.Get("/swagger/*", swaggerAuth, swagger.HandlerDefault)

	registerRoutes(app, svc)

	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}
	log.Printf("server listening on :%s", port)
	if err := app.Listen(":" + port); err != nil {
		log.Fatalf("server error: %v", err)
	}
}
</go_file>


<go_file>
<go_version> go1.23
<go_pkg> controllers

// controllers/employeeController.go
// Pattern: struct controller + constructor injection + Swagger annotations
// Observed in: Medical-App-Core/controllers/
package controllers

import (
	"net/http"
	"time"

	"hrm-api/services/contracts"
	"github.com/gofiber/fiber/v2"
)

// EmployeeController handles HTTP requests for the Employee resource.
type EmployeeController struct {
	EmployeeService contracts.EmployeeServiceContract
}

// NewEmployeeController constructs a EmployeeController with its service dependency.
func NewEmployeeController(svc contracts.EmployeeServiceContract) *EmployeeController {
	return &EmployeeController{EmployeeService: svc}
}

// CreateEmployee godoc
// @Summary     Create a new employee
// @Description Create a new employee in the system
// @Tags        Employees
// @Accept      json
// @Produce     json
// @Security    BearerAuth
// @Param       body body contracts.EmployeeInputDTO true "Employee data"
// @Success     201  {object} fiber.Map
// @Failure     400  {object} fiber.Map
// @Failure     422  {object} fiber.Map
// @Failure     500  {object} fiber.Map
// @Router      /employees [post]
func (ctrl *EmployeeController) CreateEmployee(c *fiber.Ctx) error {
	var input contracts.EmployeeInputDTO
	if err := c.BodyParser(&input); err != nil {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "invalid request payload"})
	}

	if input.DepartmentName == "" {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "department_name is required"})
	}
	if input.Position == "" {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "position is required"})
	}

	id, err := ctrl.EmployeeService.CreateFromInput(input)
	if err != nil {
		return c.Status(http.StatusUnprocessableEntity).JSON(fiber.Map{"error": err.Error()})
	}

	return c.Status(http.StatusCreated).JSON(fiber.Map{
		"message": "Employee created successfully",
		"id":      id,
	})
}

// GetByCPF godoc
// @Summary     Get employee by CPF
// @Description Retrieve a single employee identified by its CPF
// @Tags        Employees
// @Produce     json
// @Security    BearerAuth
// @Param       cpf path string true "Employee CPF"
// @Success     200 {object} contracts.EmployeeDTO
// @Failure     400 {object} fiber.Map
// @Failure     404 {object} fiber.Map
// @Router      /employees/{cpf} [get]
func (ctrl *EmployeeController) GetByCPF(c *fiber.Ctx) error {
	identifier := c.Params("cpf")
	if identifier == "" {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "cpf is required"})
	}

	result, err := ctrl.EmployeeService.FindByCPF(identifier)
	if err != nil {
		return c.Status(http.StatusNotFound).JSON(fiber.Map{"error": err.Error()})
	}

	return c.Status(http.StatusOK).JSON(result)
}

// ListEmployees godoc
// @Summary     List all employees
// @Description Returns a paginated list of employees
// @Tags        Employees
// @Produce     json
// @Security    BearerAuth
// @Param       page  query int false "Page number (default 1)"
// @Param       limit query int false "Page size (default 20)"
// @Success     200  {array}  contracts.EmployeeDTO
// @Failure     500  {object} fiber.Map
// @Router      /employees [get]
func (ctrl *EmployeeController) ListEmployees(c *fiber.Ctx) error {
	page  := c.QueryInt("page", 1)
	limit := c.QueryInt("limit", 20)
	if page < 1  { page = 1 }
	if limit < 1 { limit = 20 }

	results, err := ctrl.EmployeeService.List(page, limit)
	if err != nil {
		return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"error": "failed to retrieve employees"})
	}

	return c.Status(http.StatusOK).JSON(fiber.Map{
		"data":  results,
		"page":  page,
		"limit": limit,
	})
}
</go_file>


<go_file>
<go_version> go1.23
<go_pkg> main

// cmd/main.go — Fiber router setup
// Pattern: group-based routing + auth middleware + Swagger protection
// Observed in: Medical-App-Core/cmd/main.go
package main

import (
	"log"
	"os"

	"hrm-api/controllers"
	"hrm-api/initializers"
	_ "hrm-api/docs"

	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/basicauth"
	"github.com/gofiber/fiber/v2/middleware/cors"
	"github.com/gofiber/fiber/v2/middleware/logger"
	"github.com/gofiber/swagger"
	"github.com/joho/godotenv"
)

// bearerAuthMiddleware validates the Authorization: Bearer <token> header.
// Returns 401 if missing or invalid; calls Next() on success.
func bearerAuthMiddleware(svc *initializers.Services) fiber.Handler {
	return func(c *fiber.Ctx) error {
		header := c.Get("Authorization")
		if len(header) <= 7 || header[:7] != "Bearer " {
			return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
				"error": "missing or malformed Authorization header",
			})
		}
		if err := svc.AuthTokenService.ValidateToken(header[7:]); err != nil {
			return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
				"error":  "invalid or expired token",
				"reason": err.Error(),
			})
		}
		return c.Next()
	}
}

func configureMiddleware(app *fiber.App) {
	app.Use(cors.New(cors.Config{
		AllowOrigins: "*",
		AllowMethods: "GET,POST,PUT,PATCH,DELETE,OPTIONS",
		AllowHeaders: "Origin, Content-Type, Accept, Authorization",
	}))
	app.Use(logger.New(logger.Config{
		Format: `[$\{time\}] $\{status\} - $\{method\} $\{path\}\n`,
	}))
}

func registerRoutes(app *fiber.App, svc *initializers.Services) {
	auth := app.Group("/auth")
	auth.Post("/token",    controllers.NewAuthController(svc.AuthTokenService).GenerateToken)
	auth.Post("/validate", controllers.NewAuthController(svc.AuthTokenService).ValidateToken)

	protected := app.Group("/", bearerAuthMiddleware(svc))

	entityCtrl := controllers.NewEmployeeController(svc.EmployeeService)
	employees := protected.Group("/employees")
	employees.Post("/",              entityCtrl.CreateEmployee)
	employees.Get("/",               entityCtrl.ListEmployees)
	employees.Get("/:cpf",   entityCtrl.GetByCPF)
}

func main() {
	if err := godotenv.Load(); err != nil {
		log.Println("warning: .env file not found, using environment")
	}

	db  := initializers.InitialDB()
	initializers.RunMigrations(db)
	svc := initializers.InitServices(db)

	app := fiber.New(fiber.Config{AppName: "hrm-api v1"})
	configureMiddleware(app)

	// Swagger endpoint protected by basic auth
	swaggerUser := os.Getenv("SWAGGER_USER")
	swaggerPass := os.Getenv("SWAGGER_PASSWORD")
	if swaggerUser == "" || swaggerPass == "" {
		log.Fatal("SWAGGER_USER and SWAGGER_PASSWORD must be set")
	}
	swaggerAuth := basicauth.New(basicauth.Config{
		Users: map[string]string{swaggerUser: swaggerPass},
	})
	app.Get("/swagger/*", swaggerAuth, swagger.HandlerDefault)

	registerRoutes(app, svc)

	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}
	log.Printf("server listening on :%s", port)
	if err := app.Listen(":" + port); err != nil {
		log.Fatalf("server error: %v", err)
	}
}
</go_file>


<go_file>
<go_version> go1.24
<go_pkg> controllers

// controllers/employeeController.go
// Pattern: struct controller + constructor injection + Swagger annotations
// Observed in: Medical-App-Core/controllers/
package controllers

import (
	"net/http"
	"time"

	"hrm-api/services/contracts"
	"github.com/gofiber/fiber/v2"
)

// EmployeeController handles HTTP requests for the Employee resource.
type EmployeeController struct {
	EmployeeService contracts.EmployeeServiceContract
}

// NewEmployeeController constructs a EmployeeController with its service dependency.
func NewEmployeeController(svc contracts.EmployeeServiceContract) *EmployeeController {
	return &EmployeeController{EmployeeService: svc}
}

// CreateEmployee godoc
// @Summary     Create a new employee
// @Description Create a new employee in the system
// @Tags        Employees
// @Accept      json
// @Produce     json
// @Security    BearerAuth
// @Param       body body contracts.EmployeeInputDTO true "Employee data"
// @Success     201  {object} fiber.Map
// @Failure     400  {object} fiber.Map
// @Failure     422  {object} fiber.Map
// @Failure     500  {object} fiber.Map
// @Router      /employees [post]
func (ctrl *EmployeeController) CreateEmployee(c *fiber.Ctx) error {
	var input contracts.EmployeeInputDTO
	if err := c.BodyParser(&input); err != nil {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "invalid request payload"})
	}

	if input.DepartmentName == "" {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "department_name is required"})
	}
	if input.Position == "" {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "position is required"})
	}

	id, err := ctrl.EmployeeService.CreateFromInput(input)
	if err != nil {
		return c.Status(http.StatusUnprocessableEntity).JSON(fiber.Map{"error": err.Error()})
	}

	return c.Status(http.StatusCreated).JSON(fiber.Map{
		"message": "Employee created successfully",
		"id":      id,
	})
}

// GetByCPF godoc
// @Summary     Get employee by CPF
// @Description Retrieve a single employee identified by its CPF
// @Tags        Employees
// @Produce     json
// @Security    BearerAuth
// @Param       cpf path string true "Employee CPF"
// @Success     200 {object} contracts.EmployeeDTO
// @Failure     400 {object} fiber.Map
// @Failure     404 {object} fiber.Map
// @Router      /employees/{cpf} [get]
func (ctrl *EmployeeController) GetByCPF(c *fiber.Ctx) error {
	identifier := c.Params("cpf")
	if identifier == "" {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "cpf is required"})
	}

	result, err := ctrl.EmployeeService.FindByCPF(identifier)
	if err != nil {
		return c.Status(http.StatusNotFound).JSON(fiber.Map{"error": err.Error()})
	}

	return c.Status(http.StatusOK).JSON(result)
}

// ListEmployees godoc
// @Summary     List all employees
// @Description Returns a paginated list of employees
// @Tags        Employees
// @Produce     json
// @Security    BearerAuth
// @Param       page  query int false "Page number (default 1)"
// @Param       limit query int false "Page size (default 20)"
// @Success     200  {array}  contracts.EmployeeDTO
// @Failure     500  {object} fiber.Map
// @Router      /employees [get]
func (ctrl *EmployeeController) ListEmployees(c *fiber.Ctx) error {
	page  := c.QueryInt("page", 1)
	limit := c.QueryInt("limit", 20)
	if page < 1  { page = 1 }
	if limit < 1 { limit = 20 }

	results, err := ctrl.EmployeeService.List(page, limit)
	if err != nil {
		return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"error": "failed to retrieve employees"})
	}

	return c.Status(http.StatusOK).JSON(fiber.Map{
		"data":  results,
		"page":  page,
		"limit": limit,
	})
}
</go_file>


<go_file>
<go_version> go1.24
<go_pkg> main

// cmd/main.go — Fiber router setup
// Pattern: group-based routing + auth middleware + Swagger protection
// Observed in: Medical-App-Core/cmd/main.go
package main

import (
	"log"
	"os"

	"hrm-api/controllers"
	"hrm-api/initializers"
	_ "hrm-api/docs"

	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/basicauth"
	"github.com/gofiber/fiber/v2/middleware/cors"
	"github.com/gofiber/fiber/v2/middleware/logger"
	"github.com/gofiber/swagger"
	"github.com/joho/godotenv"
)

// bearerAuthMiddleware validates the Authorization: Bearer <token> header.
// Returns 401 if missing or invalid; calls Next() on success.
func bearerAuthMiddleware(svc *initializers.Services) fiber.Handler {
	return func(c *fiber.Ctx) error {
		header := c.Get("Authorization")
		if len(header) <= 7 || header[:7] != "Bearer " {
			return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
				"error": "missing or malformed Authorization header",
			})
		}
		if err := svc.AuthTokenService.ValidateToken(header[7:]); err != nil {
			return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
				"error":  "invalid or expired token",
				"reason": err.Error(),
			})
		}
		return c.Next()
	}
}

func configureMiddleware(app *fiber.App) {
	app.Use(cors.New(cors.Config{
		AllowOrigins: "*",
		AllowMethods: "GET,POST,PUT,PATCH,DELETE,OPTIONS",
		AllowHeaders: "Origin, Content-Type, Accept, Authorization",
	}))
	app.Use(logger.New(logger.Config{
		Format: `[$\{time\}] $\{status\} - $\{method\} $\{path\}\n`,
	}))
}

func registerRoutes(app *fiber.App, svc *initializers.Services) {
	auth := app.Group("/auth")
	auth.Post("/token",    controllers.NewAuthController(svc.AuthTokenService).GenerateToken)
	auth.Post("/validate", controllers.NewAuthController(svc.AuthTokenService).ValidateToken)

	protected := app.Group("/", bearerAuthMiddleware(svc))

	entityCtrl := controllers.NewEmployeeController(svc.EmployeeService)
	employees := protected.Group("/employees")
	employees.Post("/",              entityCtrl.CreateEmployee)
	employees.Get("/",               entityCtrl.ListEmployees)
	employees.Get("/:cpf",   entityCtrl.GetByCPF)
}

func main() {
	if err := godotenv.Load(); err != nil {
		log.Println("warning: .env file not found, using environment")
	}

	db  := initializers.InitialDB()
	initializers.RunMigrations(db)
	svc := initializers.InitServices(db)

	app := fiber.New(fiber.Config{AppName: "hrm-api v1"})
	configureMiddleware(app)

	// Swagger endpoint protected by basic auth
	swaggerUser := os.Getenv("SWAGGER_USER")
	swaggerPass := os.Getenv("SWAGGER_PASSWORD")
	if swaggerUser == "" || swaggerPass == "" {
		log.Fatal("SWAGGER_USER and SWAGGER_PASSWORD must be set")
	}
	swaggerAuth := basicauth.New(basicauth.Config{
		Users: map[string]string{swaggerUser: swaggerPass},
	})
	app.Get("/swagger/*", swaggerAuth, swagger.HandlerDefault)

	registerRoutes(app, svc)

	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}
	log.Printf("server listening on :%s", port)
	if err := app.Listen(":" + port); err != nil {
		log.Fatalf("server error: %v", err)
	}
}
</go_file>


<go_file>
<go_version> go1.24
<go_pkg> utils

// utils/responseUtil.go
// Pattern: response utility interface + JSON helper
// Observed in: Medical-App-Core/utils/responseUtil.go
package utils

import (
	"encoding/json"

	"github.com/gofiber/fiber/v2"
)

// ResponseUtil abstracts JSON response construction for testability.
type ResponseUtil interface {
	RespondWithJSON(c *fiber.Ctx, code int, payload any) error
	RespondWithError(c *fiber.Ctx, code int, message string) error
}

// JSONResponseUtil implements ResponseUtil using Fiber's context.
type JSONResponseUtil struct{}

func (ru *JSONResponseUtil) RespondWithJSON(c *fiber.Ctx, code int, payload any) error {
	body, err := json.Marshal(payload)
	if err != nil {
		return c.Status(fiber.StatusInternalServerError).
			JSON(fiber.Map{"error": "failed to marshal response"})
	}
	c.Set("Content-Type", "application/json")
	return c.Status(code).Send(body)
}

func (ru *JSONResponseUtil) RespondWithError(c *fiber.Ctx, code int, message string) error {
	return c.Status(code).JSON(fiber.Map{"error": message})
}
</go_file>


<go_file>
<go_version> go1.21
<go_pkg> controllers

// controllers/shipmentController.go
// Pattern: struct controller + constructor injection + Swagger annotations
// Observed in: Medical-App-Core/controllers/
package controllers

import (
	"net/http"
	"time"

	"logistics-api/services/contracts"
	"github.com/gofiber/fiber/v2"
)

// ShipmentController handles HTTP requests for the Shipment resource.
type ShipmentController struct {
	ShipmentService contracts.ShipmentServiceContract
}

// NewShipmentController constructs a ShipmentController with its service dependency.
func NewShipmentController(svc contracts.ShipmentServiceContract) *ShipmentController {
	return &ShipmentController{ShipmentService: svc}
}

// CreateShipment godoc
// @Summary     Create a new shipment
// @Description Create a new shipment in the system
// @Tags        Shipments
// @Accept      json
// @Produce     json
// @Security    BearerAuth
// @Param       body body contracts.ShipmentInputDTO true "Shipment data"
// @Success     201  {object} fiber.Map
// @Failure     400  {object} fiber.Map
// @Failure     422  {object} fiber.Map
// @Failure     500  {object} fiber.Map
// @Router      /shipments [post]
func (ctrl *ShipmentController) CreateShipment(c *fiber.Ctx) error {
	var input contracts.ShipmentInputDTO
	if err := c.BodyParser(&input); err != nil {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "invalid request payload"})
	}

	if input.OriginAddress == "" {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "origin_address is required"})
	}
	if input.DestinationAddress == "" {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "destination_address is required"})
	}

	id, err := ctrl.ShipmentService.CreateFromInput(input)
	if err != nil {
		return c.Status(http.StatusUnprocessableEntity).JSON(fiber.Map{"error": err.Error()})
	}

	return c.Status(http.StatusCreated).JSON(fiber.Map{
		"message": "Shipment created successfully",
		"id":      id,
	})
}

// GetByTrackingCode godoc
// @Summary     Get shipment by TrackingCode
// @Description Retrieve a single shipment identified by its TrackingCode
// @Tags        Shipments
// @Produce     json
// @Security    BearerAuth
// @Param       tracking_code path string true "Shipment TrackingCode"
// @Success     200 {object} contracts.ShipmentDTO
// @Failure     400 {object} fiber.Map
// @Failure     404 {object} fiber.Map
// @Router      /shipments/{tracking_code} [get]
func (ctrl *ShipmentController) GetByTrackingCode(c *fiber.Ctx) error {
	identifier := c.Params("tracking_code")
	if identifier == "" {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "tracking_code is required"})
	}

	result, err := ctrl.ShipmentService.FindByTrackingCode(identifier)
	if err != nil {
		return c.Status(http.StatusNotFound).JSON(fiber.Map{"error": err.Error()})
	}

	return c.Status(http.StatusOK).JSON(result)
}

// ListShipments godoc
// @Summary     List all shipments
// @Description Returns a paginated list of shipments
// @Tags        Shipments
// @Produce     json
// @Security    BearerAuth
// @Param       page  query int false "Page number (default 1)"
// @Param       limit query int false "Page size (default 20)"
// @Success     200  {array}  contracts.ShipmentDTO
// @Failure     500  {object} fiber.Map
// @Router      /shipments [get]
func (ctrl *ShipmentController) ListShipments(c *fiber.Ctx) error {
	page  := c.QueryInt("page", 1)
	limit := c.QueryInt("limit", 20)
	if page < 1  { page = 1 }
	if limit < 1 { limit = 20 }

	results, err := ctrl.ShipmentService.List(page, limit)
	if err != nil {
		return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"error": "failed to retrieve shipments"})
	}

	return c.Status(http.StatusOK).JSON(fiber.Map{
		"data":  results,
		"page":  page,
		"limit": limit,
	})
}
</go_file>


<go_file>
<go_version> go1.21
<go_pkg> main

// cmd/main.go — Fiber router setup
// Pattern: group-based routing + auth middleware + Swagger protection
// Observed in: Medical-App-Core/cmd/main.go
package main

import (
	"log"
	"os"

	"logistics-api/controllers"
	"logistics-api/initializers"
	_ "logistics-api/docs"

	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/basicauth"
	"github.com/gofiber/fiber/v2/middleware/cors"
	"github.com/gofiber/fiber/v2/middleware/logger"
	"github.com/gofiber/swagger"
	"github.com/joho/godotenv"
)

// bearerAuthMiddleware validates the Authorization: Bearer <token> header.
// Returns 401 if missing or invalid; calls Next() on success.
func bearerAuthMiddleware(svc *initializers.Services) fiber.Handler {
	return func(c *fiber.Ctx) error {
		header := c.Get("Authorization")
		if len(header) <= 7 || header[:7] != "Bearer " {
			return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
				"error": "missing or malformed Authorization header",
			})
		}
		if err := svc.AuthTokenService.ValidateToken(header[7:]); err != nil {
			return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
				"error":  "invalid or expired token",
				"reason": err.Error(),
			})
		}
		return c.Next()
	}
}

func configureMiddleware(app *fiber.App) {
	app.Use(cors.New(cors.Config{
		AllowOrigins: "*",
		AllowMethods: "GET,POST,PUT,PATCH,DELETE,OPTIONS",
		AllowHeaders: "Origin, Content-Type, Accept, Authorization",
	}))
	app.Use(logger.New(logger.Config{
		Format: `[$\{time\}] $\{status\} - $\{method\} $\{path\}\n`,
	}))
}

func registerRoutes(app *fiber.App, svc *initializers.Services) {
	auth := app.Group("/auth")
	auth.Post("/token",    controllers.NewAuthController(svc.AuthTokenService).GenerateToken)
	auth.Post("/validate", controllers.NewAuthController(svc.AuthTokenService).ValidateToken)

	protected := app.Group("/", bearerAuthMiddleware(svc))

	entityCtrl := controllers.NewShipmentController(svc.ShipmentService)
	shipments := protected.Group("/shipments")
	shipments.Post("/",              entityCtrl.CreateShipment)
	shipments.Get("/",               entityCtrl.ListShipments)
	shipments.Get("/:tracking_code",   entityCtrl.GetByTrackingCode)
}

func main() {
	if err := godotenv.Load(); err != nil {
		log.Println("warning: .env file not found, using environment")
	}

	db  := initializers.InitialDB()
	initializers.RunMigrations(db)
	svc := initializers.InitServices(db)

	app := fiber.New(fiber.Config{AppName: "logistics-api v1"})
	configureMiddleware(app)

	// Swagger endpoint protected by basic auth
	swaggerUser := os.Getenv("SWAGGER_USER")
	swaggerPass := os.Getenv("SWAGGER_PASSWORD")
	if swaggerUser == "" || swaggerPass == "" {
		log.Fatal("SWAGGER_USER and SWAGGER_PASSWORD must be set")
	}
	swaggerAuth := basicauth.New(basicauth.Config{
		Users: map[string]string{swaggerUser: swaggerPass},
	})
	app.Get("/swagger/*", swaggerAuth, swagger.HandlerDefault)

	registerRoutes(app, svc)

	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}
	log.Printf("server listening on :%s", port)
	if err := app.Listen(":" + port); err != nil {
		log.Fatalf("server error: %v", err)
	}
}
</go_file>


<go_file>
<go_version> go1.22
<go_pkg> controllers

// controllers/shipmentController.go
// Pattern: struct controller + constructor injection + Swagger annotations
// Observed in: Medical-App-Core/controllers/
package controllers

import (
	"net/http"
	"time"

	"logistics-api/services/contracts"
	"github.com/gofiber/fiber/v2"
)

// ShipmentController handles HTTP requests for the Shipment resource.
type ShipmentController struct {
	ShipmentService contracts.ShipmentServiceContract
}

// NewShipmentController constructs a ShipmentController with its service dependency.
func NewShipmentController(svc contracts.ShipmentServiceContract) *ShipmentController {
	return &ShipmentController{ShipmentService: svc}
}

// CreateShipment godoc
// @Summary     Create a new shipment
// @Description Create a new shipment in the system
// @Tags        Shipments
// @Accept      json
// @Produce     json
// @Security    BearerAuth
// @Param       body body contracts.ShipmentInputDTO true "Shipment data"
// @Success     201  {object} fiber.Map
// @Failure     400  {object} fiber.Map
// @Failure     422  {object} fiber.Map
// @Failure     500  {object} fiber.Map
// @Router      /shipments [post]
func (ctrl *ShipmentController) CreateShipment(c *fiber.Ctx) error {
	var input contracts.ShipmentInputDTO
	if err := c.BodyParser(&input); err != nil {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "invalid request payload"})
	}

	if input.OriginAddress == "" {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "origin_address is required"})
	}
	if input.DestinationAddress == "" {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "destination_address is required"})
	}

	id, err := ctrl.ShipmentService.CreateFromInput(input)
	if err != nil {
		return c.Status(http.StatusUnprocessableEntity).JSON(fiber.Map{"error": err.Error()})
	}

	return c.Status(http.StatusCreated).JSON(fiber.Map{
		"message": "Shipment created successfully",
		"id":      id,
	})
}

// GetByTrackingCode godoc
// @Summary     Get shipment by TrackingCode
// @Description Retrieve a single shipment identified by its TrackingCode
// @Tags        Shipments
// @Produce     json
// @Security    BearerAuth
// @Param       tracking_code path string true "Shipment TrackingCode"
// @Success     200 {object} contracts.ShipmentDTO
// @Failure     400 {object} fiber.Map
// @Failure     404 {object} fiber.Map
// @Router      /shipments/{tracking_code} [get]
func (ctrl *ShipmentController) GetByTrackingCode(c *fiber.Ctx) error {
	identifier := c.Params("tracking_code")
	if identifier == "" {
		return c.Status(http.StatusBadRequest).JSON(fiber.Map{"error": "tracking_code is required"})
	}

	result, err := ctrl.ShipmentService.FindByTrackingCode(identifier)
	if err != nil {
		return c.Status(http.StatusNotFound).JSON(fiber.Map{"error": err.Error()})
	}

	return c.Status(http.StatusOK).JSON(result)
}

// ListShipments godoc
// @Summary     List all shipments
// @Description Returns a paginated list of shipments
// @Tags        Shipments
// @Produce     json
// @Security    BearerAuth
// @Param       page  query int false "Page number (default 1)"
// @Param       limit query int false "Page size (default 20)"
// @Success     200  {array}  contracts.ShipmentDTO
// @Failure     500  {object} fiber.Map
// @Router      /shipments [get]
func (ctrl *ShipmentController) ListShipments(c *fiber.Ctx) error {
	page  := c.QueryInt("page", 1)
	limit := c.QueryInt("limit", 20)
	if page < 1  { page = 1 }
	if limit < 1 { limit = 20 }

	results, err := ctrl.ShipmentService.List(page, limit)
	if err != nil {
		return c.Status(http.StatusInternalServerError).JSON(fiber.Map{"error": "failed to retrieve shipments"})
	}

	return c.Status(http.StatusOK).JSON(fiber.Map{
		"data":  results,
		"page":  page,
		"limit": limit,
	})
}
</go_file>


<go_file>
<go_version> go1.22
<go_pkg> main

// cmd/main.go — Fiber router setup
// Pattern: group-based routing + auth middleware + Swagger protection
// Observed in: Medical-App-Core/cmd/main.go
package main

import (
	"log"
	"os"

	"logistics-api/controllers"
	"logistics-api/initializers"
	_ "logistics-api/docs"

	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/basicauth"
	"github.com/gofiber/fiber/v2/middleware/cors"
	"github.com/gofiber/fiber/v2/middleware/logger"
	"github.com/gofiber/swagger"
	"github.com/joho/godotenv"
)

// bearerAuthMiddleware validates the Authorization: Bearer <token> header.
// Returns 401 if missing or invalid; calls Next() on success.
func bearerAuthMiddleware(svc *initializers.Services) fiber.Handler {
	return func(c *fiber.Ctx) error {
		header := c.Get("Authorization")
		if len(header) <= 7 || header[:7] != "Bearer " {
			return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
				"error": "missing or malformed Authorization header",
			})
		}
		if err := svc.AuthTokenService.ValidateToken(header[7:]); err != nil {
			return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
				"error":  "invalid or expired token",
				"reason": err.Error(),
			})
		}
		return c.Next()
	}
}

func configureMiddleware(app *fiber.App) {
	app.Use(cors.New(cors.Config{
		AllowOrigins: "*",
		AllowMethods: "GET,POST,PUT,PATCH,DELETE,OPTIONS",
		AllowHeaders: "Origin, Content-Type, Accept, Authorization",
	}))
	app.Use(logger.New(logger.Config{
		Format: `[$\{time\}] $\{status\} - $\{method\} $\{path\}\n`,
	}))
}

func registerRoutes(app *fiber.App, svc *initializers.Services) {
	auth := app.Group("/auth")
	auth.Post("/token",    controllers.NewAuthController(svc.AuthTokenService).GenerateToken)
	auth.Post("/validate", controllers.NewAuthController(svc.AuthTokenService).ValidateToken)

	protected := app.Group("/", bearerAuthMiddleware(svc))

	entityCtrl := controllers.NewShipmentController(svc.ShipmentService)
	shipments := protected.Group("/shipments")
	shipments.Post("/",              entityCtrl.CreateShipment)
	shipments.Get("/",               entityCtrl.ListShipments)
	shipments.Get("/:tracking_code",   entityCtrl.GetByTrackingCode)
}

func main() {
	if err := godotenv.Load(); err != nil {
		log.Println("warning: .env file not found, using environment")
	}

	db  := initializers.InitialDB()
	initializers.RunMigrations(db)
	svc := initializers.InitServices(db)

	app := fiber.New(fiber.Config{AppName: "logistics-api v1"})
	configureMiddleware(app)

	// Swagger endpoint protected by basic auth
	swaggerUser := os.Getenv("SWAGGER_USER")
	swaggerPass := os.Getenv("SWAGGER_PASSWORD")
	if swaggerUser == "" || swaggerPass == "" {
		log.Fatal("SWAGGER_USER and SWAGGER_PASSWORD must be set")
	}
	swaggerAuth := basicauth.New(basicauth.Config{
		Users: map[string]string{swaggerUser: swaggerPass},
	})
	app.Get("/swagger/*", swaggerAuth, swagger.HandlerDefault)

	registerRoutes(app, svc)

	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}
	log.Printf("server listening on :%s", port)
	if err := app.Listen(":" + port); err != nil {
		log.Fatalf("server error: %v", err)
	}
}
</go_file>