package categoriesRepo

import (
	"git.ma-al.com/goc_daniel/b2b/app/db"
	"git.ma-al.com/goc_daniel/b2b/app/model"
	"git.ma-al.com/goc_daniel/b2b/app/model/dbmodel"
	constdata "git.ma-al.com/goc_daniel/b2b/app/utils/const_data"
)

type UICategoriesRepo interface {
	GetAllCategories(idLang uint) ([]model.ScannedCategory, error)
}

type CategoriesRepo struct{}

func New() UICategoriesRepo {
	return &CategoriesRepo{}
}

func (r *CategoriesRepo) GetAllCategories(idLang uint) ([]model.ScannedCategory, error) {
	var allCategories []model.ScannedCategory

	categoryTbl := (&dbmodel.PsCategory{}).TableName()
	categoryLangTbl := (&dbmodel.PsCategoryLang{}).TableName()
	categoryShopTbl := (&dbmodel.PsCategoryShop{}).TableName()
	langTbl := (&dbmodel.PsLang{}).TableName()

	err := db.Get().
		Model(dbmodel.PsCategory{}).
		Select(`
			ps_category.id_category AS category_id,
			ps_category_lang.name AS name,
			ps_category.active AS active,
			ps_category_shop.position AS position,
			ps_category.id_parent AS id_parent,
			ps_category.is_root_category AS is_root_category,
			ps_category_lang.link_rewrite AS link_rewrite,
			ps_lang.iso_code AS iso_code
		`).
		Joins(`LEFT JOIN ? ON ??.id_category = ??.id_category AND ??.id_shop = ? AND ??.id_lang = ?`,
			categoryLangTbl, categoryLangTbl, categoryTbl, categoryLangTbl, constdata.SHOP_ID, categoryLangTbl, idLang).
		Joins(`LEFT JOIN ? ON ??.id_category = ??.id_category AND ??.id_shop = ?`,
			categoryShopTbl, categoryShopTbl, categoryTbl, categoryShopTbl, constdata.SHOP_ID).
		Joins(`JOIN ? ON ??.id_lang = ??.id_lang`,
			langTbl, langTbl, categoryLangTbl).
		Scan(&allCategories).Error

	return allCategories, err
}
