package model

import (
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"src.whiteboxsystems.nl/DECOZO/okapi"
	"src.whiteboxsystems.nl/DECOZO/okapidemo/sharedmodel"
)

func GetDB(location string) (*gorm.DB, error) {
	db, err := gorm.Open(sqlite.Open(location), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		return nil, err
	}

	// Migrate the schema
	db.AutoMigrate(&sharedmodel.Registration{})
	db.AutoMigrate(&sharedmodel.Connection{})
	db.AutoMigrate(&sharedmodel.ServiceDefinition{})
	db.AutoMigrate(&sharedmodel.AuthConfig{})
	db.AutoMigrate(&sharedmodel.ProtocolConfig{})
	db.AutoMigrate(&sharedmodel.ServiceConfig{})
	db.AutoMigrate(&sharedmodel.Subscription{})

	var cnt int64
	db.Model(&sharedmodel.ServiceDefinition{}).Count(&cnt)

	if cnt == 0 {
		db.Create(&sharedmodel.ServiceDefinition{
			Name:               "Visitelijst",
			Description:        "Visitelijst voor het inzien van patientendossiers op visite",
			SubscriptionPolicy: okapi.SubscriptionPolicy_optin,
			ConsentPolicy:      okapi.ConsentPolicy_presumed,
			ServiceID:          "wbx:visitelijst",
			FetchProtocols: sharedmodel.ProtocolArray{
				{
					Protocol:    "https://whiteboxsystems.nl/protospecs/whitebox-fetch/http",
					AuthMethods: []string{"http://decozo.org/proto/auth/mtls"},
				},
			},
			PushProtocols: sharedmodel.ProtocolArray{
				{
					Protocol:    "https://whiteboxsystems.nl/protospecs/whitebox-push/http",
					AuthMethods: []string{"http://decozo.org/proto/auth/mtls"},
				},
			},
		})

		db.Create(&sharedmodel.ServiceDefinition{
			Name:               "Waarneminglijst",
			Description:        "Waarneminglijst om patienten inzichtelijk te maken op de HAP",
			SubscriptionPolicy: okapi.SubscriptionPolicy_optin,
			ConsentPolicy:      okapi.ConsentPolicy_explicit,
			ServiceID:          "wbx:waarneming",
			FetchProtocols: sharedmodel.ProtocolArray{
				{
					Protocol:    "https://whiteboxsystems.nl/protospecs/whitebox-fetch/http",
					AuthMethods: []string{"http://decozo.org/proto/auth/mtls"},
				},
			},
			PushProtocols: sharedmodel.ProtocolArray{
				{
					Protocol:    "https://whiteboxsystems.nl/protospecs/whitebox-push/http",
					AuthMethods: []string{"http://decozo.org/proto/auth/mtls"},
				},
			},
		})
	}

	db.Exec("PRAGMA foreign_keys = ON", nil)

	return db, nil
}
