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:               "MedMij DVZA",
			Description:        "MedMij compliant PGO koppeling",
			SubscriptionPolicy: okapi.SubscriptionPolicy_optout,
			ConsentPolicy:      okapi.ConsentPolicy_presumed,
			ServiceID:          "acme:dvza",
			FetchProtocols: sharedmodel.ProtocolArray{
				{
					Protocol:    "https://hl7.nl/fhir",
					AuthMethods: []string{"BearerToken"},
				},
			},
			PushProtocols: sharedmodel.ProtocolArray{},
		})
	}

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

	return db, nil
}
