package model

import (
	"log"
	"os"

	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

// Init initializes the database connection, auto-migrates models, and seeds a default post.
func Init() *gorm.DB {
	_, filerr := os.Open("./blog.db")
	db, err := gorm.Open(sqlite.Open("./blog.db"))
	if err != nil {
		log.Panic(err)
	}
	db.AutoMigrate(&Post{}, &Comment{}, &User{}, &InvalidJWT{})

	if filerr != nil {
		db.Save(&Post{
			ID:    1,
			Title: "Hello World",
			TLDR:  "introduction to ng-blog",
			Content: `
## Welcome

This is ng-blog, your simple blog written in Angular and Golang.

### Login

The default login is:
> Username: admin
>
> Password: admin
`,
		})
	}

	return db
}
