package repository

import (
	"fmt"
	"github.com/google/uuid"
	"github.com/rs/zerolog"
	"strings"
	"web-qudo-be/app/database"
	"web-qudo-be/app/database/entity"
	"web-qudo-be/app/module/article_categories/request"
	"web-qudo-be/utils/paginator"
	utilSvc "web-qudo-be/utils/service"
)

type articleCategoriesRepository struct {
	DB  *database.Database
	Log zerolog.Logger
}

// ArticleCategoriesRepository define interface of IArticleCategoriesRepository
type ArticleCategoriesRepository interface {
	GetAll(clientId *uuid.UUID, req request.ArticleCategoriesQueryRequest) (articleCategoriess []*entity.ArticleCategories, paging paginator.Pagination, err error)
	FindOne(clientId *uuid.UUID, id uint) (articleCategories *entity.ArticleCategories, err error)
	FindOneByOldId(clientId *uuid.UUID, id uint) (articleCategories *entity.ArticleCategories, err error)
	FindOneBySlug(clientId *uuid.UUID, slug string) (articleCategories *entity.ArticleCategories, err error)
	Create(articleCategories *entity.ArticleCategories) (articleCategoriesReturn *entity.ArticleCategories, err error)
	Update(clientId *uuid.UUID, id uint, articleCategories *entity.ArticleCategories) (err error)
	Delete(clientId *uuid.UUID, id uint) (err error)
}

func NewArticleCategoriesRepository(db *database.Database, log zerolog.Logger) ArticleCategoriesRepository {
	return &articleCategoriesRepository{
		DB:  db,
		Log: log,
	}
}

// implement interface of IArticleCategoriesRepository
func (_i *articleCategoriesRepository) GetAll(clientId *uuid.UUID, req request.ArticleCategoriesQueryRequest) (articleCategoriess []*entity.ArticleCategories, paging paginator.Pagination, err error) {
	var count int64

	query := _i.DB.DB.Model(&entity.ArticleCategories{})

	// Add ClientId filter
	if clientId != nil {
		query = query.Where("article_categories.client_id = ?", clientId)
	}

	if req.UserLevelId != nil {
		query = _i.DB.DB.Model(&entity.ArticleCategories{}).
			Joins("LEFT JOIN users ON article_categories.created_by_id = users.id").
			Joins("LEFT JOIN user_levels ON users.user_level_id = user_levels.id").
			Where("user_levels.id = ? or user_levels.parent_level_id = ?", *req.UserLevelId, *req.UserLevelId)

		// Add ClientId filter for joined query
		if clientId != nil {
			query = query.Where("article_categories.client_id = ?", clientId)
		}
	}

	query = query.Where("article_categories.is_active = ?", true)

	if req.Title != nil && *req.Title != "" {
		title := strings.ToLower(*req.Title)
		query = query.Where("LOWER(article_categories.title) LIKE ?", "%"+strings.ToLower(title)+"%")
	}
	if req.Description != nil && *req.Description != "" {
		description := strings.ToLower(*req.Description)
		query = query.Where("LOWER(article_categories.description) LIKE ?", "%"+strings.ToLower(description)+"%")
	}
	if req.ParentId != nil {
		query = query.Where("article_categories.parent_id = ?", req.ParentId)
	}
	if req.IsPublish != nil {
		query = query.Where("article_categories.is_publish = ?", req.IsPublish)
	}
	if req.StatusId != nil {
		query = query.Where("article_categories.status_id = ?", req.StatusId)
	}
	query.Count(&count)

	if req.Pagination.SortBy != "" {
		direction := "ASC"
		if req.Pagination.Sort == "desc" {
			direction = "DESC"
		}
		query.Order(fmt.Sprintf("%s %s", req.Pagination.SortBy, direction))
	}

	req.Pagination.Count = count
	req.Pagination = paginator.Paging(req.Pagination)

	err = query.Offset(req.Pagination.Offset).Limit(req.Pagination.Limit).Find(&articleCategoriess).Error

	if err != nil {
		return
	}

	paging = *req.Pagination

	return
}

func (_i *articleCategoriesRepository) FindOne(clientId *uuid.UUID, id uint) (articleCategories *entity.ArticleCategories, err error) {
	query := _i.DB.DB.Where("id = ?", id)

	// Add ClientId filter
	if clientId != nil {
		query = query.Where("client_id = ?", clientId)
	}

	if err := query.First(&articleCategories).Error; err != nil {
		return nil, err
	}

	return articleCategories, nil
}

func (_i *articleCategoriesRepository) FindOneByOldId(clientId *uuid.UUID, id uint) (articleCategories *entity.ArticleCategories, err error) {
	query := _i.DB.DB.Where("old_category_id = ?", id)

	// Add ClientId filter
	if clientId != nil {
		query = query.Where("client_id = ?", clientId)
	}

	if err := query.First(&articleCategories).Error; err != nil {
		return nil, err
	}

	return articleCategories, nil
}

func (_i *articleCategoriesRepository) FindOneBySlug(clientId *uuid.UUID, slug string) (articleCategories *entity.ArticleCategories, err error) {
	query := _i.DB.DB.Where("slug = ?", slug)

	// Add ClientId filter
	if clientId != nil {
		query = query.Where("client_id = ?", clientId)
	}

	if err := query.First(&articleCategories).Error; err != nil {
		return nil, err
	}

	return articleCategories, nil
}

func (_i *articleCategoriesRepository) Create(articleCategories *entity.ArticleCategories) (articleCategoriesReturn *entity.ArticleCategories, err error) {
	result := _i.DB.DB.Create(articleCategories)
	return articleCategories, result.Error
}

func (_i *articleCategoriesRepository) Update(clientId *uuid.UUID, id uint, articleCategories *entity.ArticleCategories) (err error) {
	articleCategoriesMap, err := utilSvc.StructToMap(articleCategories)
	if err != nil {
		return err
	}
	query := _i.DB.DB.Model(&entity.ArticleCategories{}).Where(&entity.ArticleCategories{ID: id})
	if clientId != nil {
		query = query.Where("client_id = ?", clientId)
	}
	return query.Updates(articleCategoriesMap).Error
}

func (_i *articleCategoriesRepository) Delete(clientId *uuid.UUID, id uint) error {
	query := _i.DB.DB.Model(&entity.ArticleCategories{}).Where("id = ?", id)
	if clientId != nil {
		query = query.Where("client_id = ?", clientId)
	}
	return query.Delete(&entity.ArticleCategories{}).Error
}
