package main

import (
	"io"

	"github.com/pocketbase/pocketbase/core"
)

func registerAPI(se *core.ServeEvent) {
	group := se.Router.Group("/api/cctv")

	group.GET("/thumb/{streamId}", func(e *core.RequestEvent) error {
		streamId := e.Request.PathValue("streamId")
		if streamId == "" {
			return e.BadRequestError("Missing stream ID", nil)
		}
		img, err := ingestService.GetThumbnail(e.Request.Context(), streamId)
		if err != nil {
			return e.InternalServerError("Failed to get thumbnail", err)
		}
		if img == nil {
			return e.NotFoundError("Thumbnail not found", nil)
		}
		e.Response.Header().Set("Content-Type", "image/jpeg")
		e.Response.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
		_, err = io.Copy(e.Response, img)
		if err != nil {
			return e.InternalServerError("Failed to write thumbnail", err)
		}
		return nil
	})

	group.GET("/live/{streamId}", func(e *core.RequestEvent) error {
		streamId := e.Request.PathValue("streamId")
		if streamId == "" {
			return e.BadRequestError("Missing stream ID", nil)
		}
		ingestService.SubscribeLive(e.Request.Context(), streamId)
		return nil
	})
}
