package main

import (
	"io"
	"mi6e4ka/yabl-api/schemas"
	"os"
	"strconv"
	"strings"

	"gorm.io/gorm"
)

func GetAllowIds() []string {
	white, _ := os.ReadFile(os.Getenv("WHITELIST_FILE"))
	whitelist := strings.Split(string(white), "\n")
	return whitelist
}

func BookCensor(bookId string) bool {
	return true
	//return slices.Contains(GetAllowIds(), bookId)
}

func GenWhitelist(db *gorm.DB, authorsFilePath string) {
	os.Remove(os.Getenv("WHITELIST_FILE"))
	authorsFile, _ := os.Open(authorsFilePath)
	authorsWLR, _ := io.ReadAll(authorsFile)
	authorsWL := strings.Split(string(authorsWLR), "\n")
	whitelist, _ := os.OpenFile(os.Getenv("WHITELIST_FILE"), os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0777)
	for _, allowAuthor := range authorsWL {
		var author schemas.Author
		var books []schemas.Book
		authorId, _ := strconv.ParseInt(allowAuthor, 10, 64)
		db.Where("id = ?", authorId).First(&author)
		db.Model(&author).Preload("Language").Preload("Authors").Association("Books").Find(&books)
		firstLine := true
		for _, book := range books {
			if len(book.Authors) != 1 || book.Language.Code != "ru" || book.Isbn == nil {
				continue
			}
			if firstLine {
				whitelist.WriteString(book.ID.String())
				firstLine = false
			} else {
				whitelist.WriteString("\n" + book.ID.String())
			}
		}
	}
}
