/*
 * SPDX-FileCopyrightText: 2023 jordi fita mas <jfita@peritasoft.com>
 * SPDX-License-Identifier: AGPL-3.0-only
 */

package main

import (
	"context"
	"errors"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"dev.tandem.ws/tandem/camper/pkg/app"
	"dev.tandem.ws/tandem/camper/pkg/database"
)

var avatarsDir = "/var/lib/camper/avatars"
var mediaDir = "/var/lib/camper/media"

func main() {
	db, err := database.New(context.Background(), os.Getenv("CAMPER_DATABASE_URL"))
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	handler, err := app.New(db, avatarsDir, mediaDir)
	if err != nil {
		log.Fatal(err)
	}
	srv := http.Server{
		Addr:         ":8080",
		Handler:      handler,
		ReadTimeout:  60 * time.Second,
		WriteTimeout: 60 * time.Second,
		IdleTimeout:  2 * time.Minute,
	}

	go func() {
		log.Printf("INFO - listening on %s\n", srv.Addr)
		if err := srv.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
			log.Fatalf("http server: %v", err)
		}
	}()

	sigCh := make(chan os.Signal, 1)
	signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
	<-sigCh
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	log.Print("INFO - stopping server")
	if err := srv.Shutdown(ctx); err != nil {
		log.Fatal(err)
	}
}
