/*
ScheduleTogether Backend
Copyright (C) 2024, Marco Vitchi Thulin

DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License version 3 for more details.

This program incorporates external libraries for certain functionalities.
These libraries are covered by their respective licenses, and their usage
agreements are as outlined in their respective documentation or source
code.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

package api

import (
	"time"

	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/middleware/jwt"
	"github.com/kataras/iris/v12/middleware/logger"
	"github.com/kataras/iris/v12/middleware/recover"

	"git.zervo.org/scheduletogether/backend/internal/api/handlers"
	"git.zervo.org/scheduletogether/backend/internal/database"
	"git.zervo.org/scheduletogether/backend/internal/workers"
	"git.zervo.org/scheduletogether/backend/pkg/helpers/config"
	"git.zervo.org/scheduletogether/backend/pkg/helpers/logging"
)

var logboi = logging.NewLogger("api.server")

// GlobalSigner and GlobalVerifier are used to store global jwt signer and verifier
var JwtSigner *jwt.Signer
var JwtVerifier *jwt.Verifier

// InitDb initializes the database
func InitDb() {
	err := database.Init()
	if err != nil {
		logboi.Fatal("Failed to initialize database: " + err.Error())
	}
}

// NewServer creates a new Iris server instance
func NewServer() *iris.Application {
	// Load configuration
	cfg, err := config.LoadConfig()
	if err != nil {
		logboi.Fatal(err.Error())
	}

	// Initialize database
	InitDb()

	// Create Iris server instance
	app := iris.New()

	// Create JWT signer
	JwtSigner = jwt.NewSigner(jwt.HS256, []byte(cfg.JWTSecret), time.Duration(cfg.JWTExpiration)*time.Minute)

	// Create JWT verifier
	JwtVerifier = jwt.NewVerifier(jwt.HS256, cfg.JWTSecret)

	// Schedule workers
	workers.ScheduleWorkers()

	// Apply common middleware
	app.Use(recover.New())
	app.Use(logger.New())

	// Configure routes (handlers)
	pingRoutes := app.Party("/ping")
	accountRoutes := app.Party("/account")
	friendRoutes := app.Party("/friends")
	userRoutes := app.Party("/users")

	// Register routes (handlers)
	handlers.PingHandler_RegisterRoutes(pingRoutes)
	handlers.AccountHandler_RegisterRoutes(accountRoutes)
	handlers.FriendsHandler_RegisterRoutes(friendRoutes)
	handlers.UsersHandler_RegisterRoutes(userRoutes)

	return app
}