package main

import (
	"log"
	"net/http"

	"git.balsys.eu.org/tomas/pocketbase/lubinui"
	"git.balsys.eu.org/tomas/pocketbase/ui"
	"github.com/pocketbase/pocketbase"
	"github.com/pocketbase/pocketbase/apis"
	"github.com/pocketbase/pocketbase/core"
)

func main() {
	app := pocketbase.New()

	app.OnServe().BindFunc(routes)

	app.OnRecordViewRequest().BindFunc(addLastModified)

	app.OnRecordUpdateRequest().BindFunc(ifUnmodifiedSince)

	app.OnRecordDeleteRequest().BindFunc(ifUnmodifiedSince)

	if err := app.Start(); err != nil {
		log.Fatal(err)
	}
}

func routes(se *core.ServeEvent) error {
	se.Router.GET("/admin/{path...}", apis.Static(ui.DistDirFS, false)).
		BindFunc(routeAdmin).
		Bind(apis.Gzip())

	se.Router.GET("/{path...}", apis.Static(lubinui.DistDirFS, true)).
		BindFunc(routeRoot).
		Bind(apis.Gzip())

	return se.Next()
}

func routeAdmin(e *core.RequestEvent) error {
	// ignore root path
	if e.Request.PathValue(apis.StaticWildcardParam) != "" {
		e.Response.Header().Set("Cache-Control", "max-age=1209600, stale-while-revalidate=86400")
	}

	// add a default CSP
	if e.Response.Header().Get("Content-Security-Policy") == "" {
		e.Response.Header().Set("Content-Security-Policy", "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' http://127.0.0.1:* https://tile.openstreetmap.org data: blob:; connect-src 'self' http://127.0.0.1:* https://nominatim.openstreetmap.org; script-src 'self' 'sha256-GRUzBA7PzKYug7pqxv5rJaec5bwDCw1Vo6/IXwvD3Tc='")
	}

	return e.Next()
}

func routeRoot(e *core.RequestEvent) error {
	// ignore root path
	if e.Request.PathValue(apis.StaticWildcardParam) != "" {
		e.Response.Header().Set("Cache-Control", "max-age=1209600, stale-while-revalidate=86400")
	}

	return e.Next()
}

func addLastModified(e *core.RecordRequestEvent) error {
	updated := e.Record.GetString("updated")

	if updated != "" {
		e.Response.Header().Add("Last-Modified", updated)
	}

	return e.Next()
}

func ifUnmodifiedSince(e *core.RecordRequestEvent) error {
	updated := e.Record.GetString("updated")

	if updated != "" {
		header := e.Request.Header.Get("If-Unmodified-Since")

		if header == "" || header != updated {
			e.Response.Header().Add("Last-Modified", updated)

			if header == "" {
				return e.Error(http.StatusPreconditionRequired, "Header If-Unmodified-Since is required", nil)
			} else if header != updated {
				return e.Error(http.StatusPreconditionFailed, "Record was modified after retrieval", nil)
			}
		}
	}

	return e.Next()
}
