package migrations

import (
	"git.koval.net/cyclane/cctv/server/models"
	"github.com/pocketbase/pocketbase/core"
	m "github.com/pocketbase/pocketbase/migrations"
	"github.com/pocketbase/pocketbase/tools/types"
)

const (
	colCameras = "cameras"
	colStreams = "streams"
)

func init() {
	m.Register(func(app core.App) error {
		cameras := core.NewBaseCollection(colCameras)
		cameras.Fields.Add(
			&core.TextField{
				Name:     "name",
				Required: true,
			},
			&core.TextField{
				Name: "onvif_host",
			},
			&core.TextField{
				Name:     "username",
				Required: true,
			},
			&core.TextField{
				Name:     models.CameraFPassword,
				Required: true,
			},
		)
		cameras.Fields.Add(createdUpdatedFields()...)
		cameras.CreateRule = types.Pointer("@request.auth.id != \"\"")
		cameras.ViewRule = types.Pointer("@request.auth.id != \"\"")
		cameras.ListRule = types.Pointer("@request.auth.id != \"\"")
		if err := app.Save(cameras); err != nil {
			return err
		}
		streams := core.NewBaseCollection(colStreams)
		streams.Fields.Add(
			&core.RelationField{
				Name:          models.StreamFCamera,
				Required:      true,
				CascadeDelete: true,
				CollectionId:  cameras.Id,
			},
			&core.TextField{
				Name:     "url",
				Required: true,
			},
			&core.NumberField{
				Name:     "fps",
				Required: true,
				Min:      types.Pointer[float64](0),
			},
			&core.NumberField{
				Name:     "height",
				Required: true,
				OnlyInt:  true,
				Min:      types.Pointer[float64](0),
			},
			&core.NumberField{
				Name:     "width",
				Required: true,
				OnlyInt:  true,
				Min:      types.Pointer[float64](0),
			},
		)
		streams.ViewRule = types.Pointer("@request.auth.id != \"\"")
		streams.ListRule = types.Pointer("@request.auth.id != \"\"")
		if err := app.Save(streams); err != nil {
			return err
		}
		cameras.Fields.Add(
			&core.RelationField{
				Name:         models.CameraFRecordStream,
				CollectionId: streams.Id,
			},
		)
		return app.Save(cameras)
	}, func(app core.App) error {
		cameras, err := app.FindCollectionByNameOrId(colCameras)
		if err != nil {
			return err
		}
		streams, err := app.FindCollectionByNameOrId(colStreams)
		if err != nil {
			return err
		}
		cameras.Fields.RemoveByName(models.CameraFRecordStream)
		if err := app.Save(cameras); err != nil {
			return err
		}
		if err := app.Delete(streams); err != nil {
			return err
		}
		return app.Delete(cameras)
	})
}
