package model

import (
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"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
	}

	db.AutoMigrate(&ServiceProvider{})
	db.AutoMigrate(&sharedmodel.AuthConfig{})
	db.AutoMigrate(&Service{})
	db.AutoMigrate(&Patient{})
	db.AutoMigrate(&Consent{})

	patCnt := int64(0)
	db.Model(&Patient{}).Count(&patCnt)

	if patCnt == 0 {
		patients := []Patient{
			{
				ExternalId:       "229922999",
				ExternalIdSystem: "http://fhir.nl/fhir/NamingSystem/bsn",
				Name:             "C. Bries",
				Birthdate:        "1927-05-05",
				PatientID:        "1",
				FileBase:         "cbries",
			},
			{
				ExternalId:       "383443830",
				ExternalIdSystem: "http://fhir.nl/fhir/NamingSystem/bsn",
				Name:             "J. Korts",
				Birthdate:        "1984-01-01",
				PatientID:        "2",
				FileBase:         "jkorts",
			},
		}

		db.Create(patients)
	}

	return db, nil
}
